2011-11-25 76 views
1

我试图从Matplotlib运行演示代码:legend_picking exampleMatplotlib演示代码不起作用

当代码被点击时,这段代码应该隐藏并显示绘图线。

看来,事件'pick_event'没有被激发,当我点击图例上的行。 我没有问题与simple picking example

""" 
# Enable picking on the legend to toggle the legended line on and off 
""" 
import numpy as np 
import matplotlib.pyplot as plt 

t = np.arange(0.0, 0.2, 0.1) 
y1 = 2*np.sin(2*np.pi*t) 
y2 = 4*np.sin(2*np.pi*2*t) 

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.set_title('Click on legend line to toggle line on/off') 
line1, = ax.plot(t, y1, lw=2, color='red', label='1 HZ') 
line2, = ax.plot(t, y2, lw=2, color='blue', label='2 HZ') 
leg = ax.legend(loc='upper left', fancybox=True, shadow=True) 
leg.get_frame().set_alpha(0.4) 


# we will set up a dict mapping legend line to orig line, and enable 
# picking on the legend line 
lines = [line1, line2] 
lined = dict() 
for legline, origline in zip(leg.get_lines(), lines): 
    legline.set_picker(5) # 5 pts tolerance 
    lined[legline] = origline 


def onpick(event): 
    # on the pick event, find the orig line corresponding to the 
    # legend proxy line, and toggle the visibilit 
    legline = event.artist 
    origline = lined[legline] 
    vis = not origline.get_visible() 
    origline.set_visible(vis) 
    # Change the alpha on the line in the legend so we can see what lines 
    # have been toggled 
    if vis: 
     legline.set_alpha(1.0) 
    else: 
     legline.set_alpha(0.2) 
    fig.canvas.draw() 

fig.canvas.mpl_connect('pick_event', onpick) 

plt.show() 
+1

它是否给出任何错误消息?对我来说它起作用(Matplotlib 1.0.1)。 – joris

+0

没有任何消息......当我直接点击图上的线条时,我能够触发一个事件处理程序。也许我没有很好地描绘传奇线和情节线之间的对应关系。我在VirtualBox的Mint Linux中运行它。 – tos

回答

1

您正在运行matplotlib的哪个版本?对我来说工作得很好(版本1.1.0)。在sourceforge网站上有多个示例不适用于1.0以下的版本。要找出版本号,请使用

import matplotlib 
print matplotlib.__version__ 
+0

感谢您的提示。我运行的是0.99.3版本。我要升级并会让你知道。 – tos

+0

我升级到1.1.0。有用 !出于某种原因,0.99.3是Mint Linux上的最新版本。我不得不从源头重建数据包,在这个过程中失去了后端。浪费了几个小时后,我准备好了。谢谢振亚。 – tos

0

它的工作。只需点击图例中的线条即可。

脚本应该通过点击图例中的行来切换图形的透明度。

+0

我点击图例上的线条。而且这对我来说不起作用。而且我的目标非常好。 – tos

+0

如果您希望拾取器对图表的行进行反应,请在行声明中添加“picker = 5”(或任意数量> 0)。例如:'line1,= ax.plot(t,y1,lw = 2,color ='red',label ='1 HZ',picker = 5)'。但是,您需要更改处理程序代码。 – lbolla

+0

是的,我没有问题直接点击情节。唯一的问题是,当这条线不可见时,你不知道在哪里点击将它带回... – tos