plt7_legend.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # View more python tutorials on my Youtube and Youku channel!!!
  2. # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
  3. # Youku video tutorial: http://i.youku.com/pythontutorial
  4. # 7 - legend
  5. """
  6. Please note, this script is for python3+.
  7. If you are using python2+, please modify it accordingly.
  8. Tutorial reference:
  9. http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html
  10. """
  11. import matplotlib.pyplot as plt
  12. import numpy as np
  13. x = np.linspace(-3, 3, 50)
  14. y1 = 2*x + 1
  15. y2 = x**2
  16. plt.figure()
  17. # set x limits
  18. plt.xlim((-1, 2))
  19. plt.ylim((-2, 3))
  20. # set new sticks
  21. new_sticks = np.linspace(-1, 2, 5)
  22. plt.xticks(new_sticks)
  23. # set tick labels
  24. plt.yticks([-2, -1.8, -1, 1.22, 3],
  25. [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
  26. l1, = plt.plot(x, y1, label='linear line')
  27. l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
  28. plt.legend(loc='upper right')
  29. # plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
  30. # the "," is very important in here l1, = plt... and l2, = plt... for this step
  31. """legend( handles=(line1, line2, line3),
  32. labels=('label1', 'label2', 'label3'),
  33. 'upper right')
  34. The *loc* location codes are::
  35. 'best' : 0, (currently not supported for figure legends)
  36. 'upper right' : 1,
  37. 'upper left' : 2,
  38. 'lower left' : 3,
  39. 'lower right' : 4,
  40. 'right' : 5,
  41. 'center left' : 6,
  42. 'center right' : 7,
  43. 'lower center' : 8,
  44. 'upper center' : 9,
  45. 'center' : 10,"""
  46. plt.show()