2013-08-22 32 views
7

我的代码使用matplotib从数据生成了一些图,我希望能够通过它们在现场演示中向前和向后滚动(也许通过按向前和向后键或使用鼠标)。目前,我必须将每个图像另存为一个图像,然后使用单独的图像查看器滚动浏览它们。有没有什么办法完全从python内完成?通过matplotlib图向后滚动

+0

是否需要花费时间为您生成这些情节?即'按下按钮 - >生成一个图 - >显示它等等。 –

+0

@AleksanderLidtke我可以直接生成它们,但是如何通过我创建的图表向前和向后滚动? – phoenix

+0

回调。请参阅http://matplotlib.org/users/event_handling.html。目前来看,这个问题太广泛了。 – tacaswell

回答

9

一种简单的方法来实现,在一个列表中存储所述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() 

在此代码中,我选择rightleft箭头来迭代,但您可以更改它们。

+0

非常感谢jabaldonedo ---你的例子现在在我的项目中,所以我可以为其他人确认它的工作原理。在我的例子中,'key_event'是装饰器内的闭包内的闭包。我不明白原因---所以帮助我,在上一行结束时这不是错误的标点符号---但我一直得到“未定义全局名称curr_pos”,尽管事实上它明确地由'curr_pos = 0'。我选择了'if not hasattr(key_event,“curr_pos”):key_event.curr_pos = 0'来代替'global curr_pos'的解决方案。如果需要,我会使用'key_event .__ dict __ = {}'来重置。 –