条形图

这是简单的条形图,在单个条形图上带有误差条形图和高度标签。

简单的条形图示;

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
  4. women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
  5. ind = np.arange(len(men_means)) # the x locations for the groups
  6. width = 0.35 # the width of the bars
  7. fig, ax = plt.subplots()
  8. rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
  9. color='SkyBlue', label='Men')
  10. rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
  11. color='IndianRed', label='Women')
  12. # Add some text for labels, title and custom x-axis tick labels, etc.
  13. ax.set_ylabel('Scores')
  14. ax.set_title('Scores by group and gender')
  15. ax.set_xticks(ind)
  16. ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
  17. ax.legend()
  18. def autolabel(rects, xpos='center'):
  19. """
  20. Attach a text label above each bar in *rects*, displaying its height.
  21. *xpos* indicates which side to place the text w.r.t. the center of
  22. the bar. It can be one of the following {'center', 'right', 'left'}.
  23. """
  24. xpos = xpos.lower() # normalize the case of the parameter
  25. ha = {'center': 'center', 'right': 'left', 'left': 'right'}
  26. offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} # x_txt = x + w*off
  27. for rect in rects:
  28. height = rect.get_height()
  29. ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
  30. '{}'.format(height), ha=ha[xpos], va='bottom')
  31. autolabel(rects1, "left")
  32. autolabel(rects2, "right")
  33. plt.show()

下载这个示例