我的代码使用 matplotib 从数据中生成了一些图表,我希望能够在现场演示中向前和向后滚动它们(可能通过按向前和向后键或使用鼠标)。目前我必须将每个单独保存为图像,然后使用单独的图像查看器滚动浏览它们。有没有办法完全从 python 中做到这一点?
最佳答案
一个简单的实现方法是在列表中存储 x 和 y 数组的元组,然后使用处理程序事件选择要绘制的下一个 (x,y) 对:
import numpy as np
import matplotlib.pyplot as plt
# define your x and y arrays to be plotted
t = np.linspace(start=0, stop=2*np.pi, num=100)
y1 = np.cos(t)
y2 = np.sin(t)
y3 = np.tan(t)
plots = [(t,y1), (t,y2), (t,y3)]
# now the real code :)
curr_pos = 0
def key_event(e):
global curr_pos
if e.key == "right":
curr_pos = curr_pos + 1
elif e.key == "left":
curr_pos = curr_pos - 1
else:
return
curr_pos = curr_pos % len(plots)
ax.cla()
ax.plot(plots[curr_pos][0], plots[curr_pos][1])
fig.canvas.draw()
fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', key_event)
ax = fig.add_subplot(111)
ax.plot(t,y1)
plt.show()
在此代码中,我选择了 right
和 left
箭头进行迭代,但您可以更改它们。
关于python - 通过 matplotlib 图向后和向前滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18390461/