Matplotlib示例代码无法运行
我正在尝试运行Matplotlib的示例代码:这个legend_picking示例。
这段代码应该是在点击图例时隐藏和显示图表中的线条。
但是,当我点击图例中的线条时,似乎没有触发'pick_event'这个事件。
我在简单选择示例中没有遇到这个问题。
"""
# 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()
2 个回答
0
这个功能是可以用的。只要点击图例中的线条就行。
这个脚本的作用是通过点击图例中的线条来切换图表的透明度。
1
你现在用的是什么版本的 matplotlib
呢?对我来说(版本 1.1.0
)运行得很好。在sourceforge网站上有很多例子,但在 1.0
之前的版本上可能都不太好用。要查看你当前的版本号,可以使用下面的代码:
import matplotlib
print matplotlib.__version__