简体   繁体   English

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

[英]Scroll backwards and forwards through matplotlib plots

My code produces a number of plots from data using matplotib and I would like to be able to scroll forwards and backwards through them in a live demonstration (maybe by pressing the forwards and backwards keys or using the mouse). 我的代码使用matplotib从数据中生成了许多图表,我希望能够在现场演示中向前和向后滚动它们(可能是通过按向前和向后键或使用鼠标)。 Currently I have to save each one as an image separately and then use a separate image viewer to scroll through them. 目前,我必须将每个图像单独保存为图像,然后使用单独的图像查看器滚动它们。 Is there any way of doing this entirely from within python? 有没有办法完全从python中做到这一点?

An easy way to achieve that is storing in a list a tuple of the x and y arrays and then use a handler event that picks the next (x,y) pair to be plotted: 实现这一目标的一种简单方法是在列表中存储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()

In this code I choose the right and left arrows to iterate, but you can change them. 在此代码中,我选择rightleft箭头进行迭代,但您可以更改它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM