1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| 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, ax = plt.subplots() 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)
lines = [line1, line2] lined = dict() for legline, origline in zip(leg.get_lines(), lines): legline.set_picker(5) lined[legline] = origline
def onpick(event): legline = event.artist origline = lined[legline] vis = not origline.get_visible() origline.set_visible(vis) 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()
|