图例选择

启用图例上的拾取以打开和关闭原始线。

图例选择

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. t = np.arange(0.0, 0.2, 0.1)
  4. y1 = 2*np.sin(2*np.pi*t)
  5. y2 = 4*np.sin(2*np.pi*2*t)
  6. fig, ax = plt.subplots()
  7. ax.set_title('Click on legend line to toggle line on/off')
  8. line1, = ax.plot(t, y1, lw=2, color='red', label='1 HZ')
  9. line2, = ax.plot(t, y2, lw=2, color='blue', label='2 HZ')
  10. leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
  11. leg.get_frame().set_alpha(0.4)
  12. # we will set up a dict mapping legend line to orig line, and enable
  13. # picking on the legend line
  14. lines = [line1, line2]
  15. lined = dict()
  16. for legline, origline in zip(leg.get_lines(), lines):
  17. legline.set_picker(5) # 5 pts tolerance
  18. lined[legline] = origline
  19. def onpick(event):
  20. # on the pick event, find the orig line corresponding to the
  21. # legend proxy line, and toggle the visibility
  22. legline = event.artist
  23. origline = lined[legline]
  24. vis = not origline.get_visible()
  25. origline.set_visible(vis)
  26. # Change the alpha on the line in the legend so we can see what lines
  27. # have been toggled
  28. if vis:
  29. legline.set_alpha(1.0)
  30. else:
  31. legline.set_alpha(0.2)
  32. fig.canvas.draw()
  33. fig.canvas.mpl_connect('pick_event', onpick)
  34. plt.show()

下载这个示例