plt11_bar.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. # 11 - bar
  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. n = 12
  14. X = np.arange(n)
  15. Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
  16. Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
  17. plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
  18. plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
  19. for x, y in zip(X, Y1):
  20. # ha: horizontal alignment
  21. # va: vertical alignment
  22. plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
  23. for x, y in zip(X, Y2):
  24. # ha: horizontal alignment
  25. # va: vertical alignment
  26. plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
  27. plt.xlim(-.5, n)
  28. plt.xticks(())
  29. plt.ylim(-1.25, 1.25)
  30. plt.yticks(())
  31. plt.show()