带有 matplotlib 的交互式图表

时间:2021-06-07 07:25:35

标签: python matplotlib interactive

我在 matplotlib 中创建了一个图表,当我点击它时,会绘制一个线条光标。到目前为止,一切正常。但是当我使用 twinx() 方法引入第二个 y 轴时,光标只绘制一次。第一次点击后,图表的交互性丢失。

我使用了下一个类对象来创建游标:

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()

问题是图表一直响应鼠标点击,但没有绘制光标所在的线。

0 个答案:

没有答案