一、柱状图(bar/barh)

改变柱子属性

每个柱子都是一个 rectangle 对象,其上包含很多对象,包含设置可见度,边框,hatch(图文样式)等等属性。

柱子添加高度值

其实原生函数没有这个方法,只能通过 plt.text 或者 plt.annotate 方式进行。

  1. import matplotlib
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. labels = ['G1', 'G2', 'G3', 'G4', 'G5']
  5. men_means = [20, 34, 30, 35, 27]
  6. women_means = [25, 32, 34, 20, 25]
  7. x = np.arange(len(labels)) # the label locations
  8. width = 0.35 # the width of the bars
  9. fig, ax = plt.subplots()
  10. rects1 = ax.bar(x - width/2, men_means, width, label='Men')
  11. rects2 = ax.bar(x + width/2, women_means, width, 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(x)
  16. ax.set_xticklabels(labels)
  17. ax.legend()
  18. def autolabel(rects):
  19. """Attach a text label above each bar in *rects*, displaying its height."""
  20. for rect in rects:
  21. height = rect.get_height()
  22. ax.annotate('{}'.format(height),
  23. xy=(rect.get_x() + rect.get_width() / 2, height),
  24. xytext=(0, 3), # 3 points vertical offset
  25. textcoords="offset points",
  26. ha='center', va='bottom')
  27. autolabel(rects1)
  28. autolabel(rects2)
  29. fig.tight_layout()
  30. plt.show()

Rectangle Object - 图1