python - 使用 matplotlib 的交互式图表
问题描述
我在 matplotlib 中创建了一个图表,当我单击它时,会绘制一个线形光标。到目前为止,一切正常。但是当我使用该方法引入第二个 y 轴时twinx()
,光标只绘制一次。第一次点击后,图表的交互性就丧失了。
我使用了下一个类对象来创建游标:
class SnaptoCursor(object):
def __init__(self, ax1, ax2, x, y):
self.ax1 = ax1
self.ax2 = ax2
self.lx = ax1.axhline(color='k', linewidth=0.5) # the horiz line
self.x = x
self.y = y
# text location in axes coords
self.txt = ax1.text(0.05, 0.9, '', transform=ax1.transAxes)
def mouse_click(self, event):
if not event.inaxes:
return
y = event.ydata
indx = min(np.searchsorted(self.y, y), len(self.y) - 1)
x = self.x[indx]
y = self.y[indx]
# update the line positions
if event.button == 1:
self.lx.set_ydata(y)
self.txt.set_text(
't=%1.1f [min], ΔE=%1.1f' %
(x, y))
self.ax1.figure.canvas.draw()
self.ax2.figure.canvas.draw()
为了创建图表,我使用了下一个代码:
figure = plt.figure()
ax1 = plt.subplot2grid((2,2),(1,0),1,2)
ax2 = ax1.twinx()
ax2.plot(time, energy, linewidth=1.5, color='blue', linestyle='--')
ax1.plot(time, DeltaE, linewidth=1.5, label='ΔE', color='black')
ax1.set(xlim=[0,175], xlabel='time [min]', ylabel='ΔE', title='ΔE progression')
ax2.set_ylabel('Energy [uJ]', color='blue')
ax2.spines['right'].set_color('blue')
ax2.tick_params(axis='y', colors='blue')
snap_cursor = SnaptoCursor(ax1, ax2, ax4, time, DeltaE, images)
plt.connect('button_press_event', snap_cursor.mouse_click)
plt.show()
问题是图表一直响应鼠标点击,但没有绘制光标线。
解决方案
推荐阅读
- r - 为什么我不能在 R 中将两个文件与 left_join 合并?
- c++ - realloc 在 C++ 中关于额外空间的行为如何?
- javascript - 单击弹出对话框时,ReactJs down 元素被选中
- django - 如何在发送邮件之前验证电子邮件并查找邮件是否发送 - django
- python - 熊猫重复显示非重复行
- macos - 找不到证书提供程序 Mac OS
- r - 我的列的总和似乎没有在 R 中给我正确的结果
- mocha.js - 如何在报告中获取运行详细信息和日志,而不是显示方法本身
- javascript - Vuejs v-dialog 获取数组中的最后一个元素
- docker - 针对 ASP.NET Core 5 Docker API 的 VueJS Windows 身份验证未出现