通过matplotlib图表向后和向前滚动

pho*_*nix 10 python matplotlib

我的代码使用matplotib从数据中生成了许多图表,我希望能够在现场演示中向前和向后滚动它们(可能是通过按向前和向后键或使用鼠标).目前,我必须将每个图像单独保存为图像,然后使用单独的图像查看器滚动它们.有没有办法完全从python中做到这一点?

jab*_*edo 17

实现这一目标的一种简单方法是在列表中存储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()
Run Code Online (Sandbox Code Playgroud)

在这段代码中,我选择rightleft箭头迭代,但你可以改变它们.