plt16_grid_subplot.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. # 16 - grid
  5. """
  6. Please note, this script is for python3+.
  7. If you are using python2+, please modify it accordingly.
  8. Tutorial reference:
  9. http://matplotlib.org/users/gridspec.html
  10. """
  11. import matplotlib.pyplot as plt
  12. import matplotlib.gridspec as gridspec
  13. # method 1: subplot2grid
  14. ##########################
  15. plt.figure()
  16. ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # stands for axes
  17. ax1.plot([1, 2], [1, 2])
  18. ax1.set_title('ax1_title')
  19. ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
  20. ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
  21. ax4 = plt.subplot2grid((3, 3), (2, 0))
  22. ax4.scatter([1, 2], [2, 2])
  23. ax4.set_xlabel('ax4_x')
  24. ax4.set_ylabel('ax4_y')
  25. ax5 = plt.subplot2grid((3, 3), (2, 1))
  26. # method 2: gridspec
  27. #########################
  28. plt.figure()
  29. gs = gridspec.GridSpec(3, 3)
  30. # use index from 0
  31. ax6 = plt.subplot(gs[0, :])
  32. ax7 = plt.subplot(gs[1, :2])
  33. ax8 = plt.subplot(gs[1:, 2])
  34. ax9 = plt.subplot(gs[-1, 0])
  35. ax10 = plt.subplot(gs[-1, -2])
  36. # method 3: easy to define structure
  37. ####################################
  38. f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
  39. ax11.scatter([1,2], [1,2])
  40. plt.tight_layout()
  41. plt.show()