python - 更改十字准线 matplotlib 光标示例的起始位置
问题描述
绘制时的捕捉光标从 (0,0) 开始,使我的图表非常小。
我认为代码是这样制作的,最初十字准线从(0,0)开始,但我不知道如何改变它。
捕捉光标的代码(链接在这里):
import numpy as np
import matplotlib.pyplot as plt
class SnappingCursor:
"""
A cross hair cursor that snaps to the data point of a line, which is
closest to the *x* position of the cursor.
For simplicity, this assumes that *x* values of the data are sorted.
"""
def __init__(self, ax, line):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
self.x, self.y = line.get_data()
self._last_index = None
# text location in axes coords
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
self._last_index = None
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
index = min(np.searchsorted(self.x, x), len(self.x) - 1)
if index == self._last_index:
return # still on the same data point. Nothing to do.
self._last_index = index
x = self.x[index]
y = self.y[index]
# update the line positions
self.horizontal_line.set_ydata(y)
self.vertical_line.set_xdata(x)
self.text.set_text('x=%1.2f, y=%1.2f' % (x, y))
self.ax.figure.canvas.draw()
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Snapping cursor')
line, = ax.plot(x, y, 'o')
print(line)
snap_cursor = SnappingCursor(ax, line)
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.on_mouse_move)
plt.show()
解决方案
我认为您必须设置水平线的初始位置。__init__()
应该是:
def __init__(self, ax, line):
self.ax = ax
self.x, self.y = line.get_data()
self.horizontal_line = ax.axhline(y=self.y[0], xmin=self.x[0], xmax=self.x[-1], color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
self._last_index = None
# text location in axes coords
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
这对我有用!
推荐阅读
- javascript - 用数据库中的文本替换占位符
- javascript - 使用 useState 和 useEffect 时出现“TypeError:无法读取未定义的属性‘名称’”
- python - 为什么我不能用 django 加载图像?
- jenkins - 在 Kubernetes 中挂载持久“动态”文件的解决方案
- mysql - 对于这种复杂的场景,是否可以在 SQL 中使用递归 CTE 来做到这一点?请建议我任何替代方式
- python - 通过 python 和 EWS 为 Exchange 帐户添加新委托
- extjs - ExtJS 6 tabindex 坏了
- react-native - AWS Cognito Pre Sign Up 触发器未针对托管 UI 运行 Google Auth 需要添加出生日期属性
- javascript - Mapbox GL JS - 将弹出标记与地理定位相结合
- python-3.x - Python3使用单词+字符拆分列表