条形图演示

使用Matplotlib的许多形状和大小的条形图。

条形图对于可视化计数或带有误差栏的汇总统计信息非常有用。这些示例显示了使用Matplotlib执行此操作的几种方法。

  1. # Credit: Josh Hemann
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib.ticker import MaxNLocator
  5. from collections import namedtuple
  6. n_groups = 5
  7. means_men = (20, 35, 30, 35, 27)
  8. std_men = (2, 3, 4, 1, 2)
  9. means_women = (25, 32, 34, 20, 25)
  10. std_women = (3, 5, 2, 3, 3)
  11. fig, ax = plt.subplots()
  12. index = np.arange(n_groups)
  13. bar_width = 0.35
  14. opacity = 0.4
  15. error_config = {'ecolor': '0.3'}
  16. rects1 = ax.bar(index, means_men, bar_width,
  17. alpha=opacity, color='b',
  18. yerr=std_men, error_kw=error_config,
  19. label='Men')
  20. rects2 = ax.bar(index + bar_width, means_women, bar_width,
  21. alpha=opacity, color='r',
  22. yerr=std_women, error_kw=error_config,
  23. label='Women')
  24. ax.set_xlabel('Group')
  25. ax.set_ylabel('Scores')
  26. ax.set_title('Scores by group and gender')
  27. ax.set_xticks(index + bar_width / 2)
  28. ax.set_xticklabels(('A', 'B', 'C', 'D', 'E'))
  29. ax.legend()
  30. fig.tight_layout()
  31. plt.show()

条形图演示

这个例子来自一个应用程序,在这个应用程序中,小学体育教师希望能够向父母展示他们的孩子在一些健身测试中的表现,而且重要的是,相对于其他孩子的表现。 为了演示目的提取绘图代码,我们只为小Johnny Doe编制一些数据……

  1. Student = namedtuple('Student', ['name', 'grade', 'gender'])
  2. Score = namedtuple('Score', ['score', 'percentile'])
  3. # GLOBAL CONSTANTS
  4. testNames = ['Pacer Test', 'Flexed Arm\n Hang', 'Mile Run', 'Agility',
  5. 'Push Ups']
  6. testMeta = dict(zip(testNames, ['laps', 'sec', 'min:sec', 'sec', '']))
  7. def attach_ordinal(num):
  8. """helper function to add ordinal string to integers
  9. 1 -> 1st
  10. 56 -> 56th
  11. """
  12. suffixes = {str(i): v
  13. for i, v in enumerate(['th', 'st', 'nd', 'rd', 'th',
  14. 'th', 'th', 'th', 'th', 'th'])}
  15. v = str(num)
  16. # special case early teens
  17. if v in {'11', '12', '13'}:
  18. return v + 'th'
  19. return v + suffixes[v[-1]]
  20. def format_score(scr, test):
  21. """
  22. Build up the score labels for the right Y-axis by first
  23. appending a carriage return to each string and then tacking on
  24. the appropriate meta information (i.e., 'laps' vs 'seconds'). We
  25. want the labels centered on the ticks, so if there is no meta
  26. info (like for pushups) then don't add the carriage return to
  27. the string
  28. """
  29. md = testMeta[test]
  30. if md:
  31. return '{0}\n{1}'.format(scr, md)
  32. else:
  33. return scr
  34. def format_ycursor(y):
  35. y = int(y)
  36. if y < 0 or y >= len(testNames):
  37. return ''
  38. else:
  39. return testNames[y]
  40. def plot_student_results(student, scores, cohort_size):
  41. # create the figure
  42. fig, ax1 = plt.subplots(figsize=(9, 7))
  43. fig.subplots_adjust(left=0.115, right=0.88)
  44. fig.canvas.set_window_title('Eldorado K-8 Fitness Chart')
  45. pos = np.arange(len(testNames))
  46. rects = ax1.barh(pos, [scores[k].percentile for k in testNames],
  47. align='center',
  48. height=0.5, color='m',
  49. tick_label=testNames)
  50. ax1.set_title(student.name)
  51. ax1.set_xlim([0, 100])
  52. ax1.xaxis.set_major_locator(MaxNLocator(11))
  53. ax1.xaxis.grid(True, linestyle='--', which='major',
  54. color='grey', alpha=.25)
  55. # Plot a solid vertical gridline to highlight the median position
  56. ax1.axvline(50, color='grey', alpha=0.25)
  57. # set X-axis tick marks at the deciles
  58. cohort_label = ax1.text(.5, -.07, 'Cohort Size: {0}'.format(cohort_size),
  59. horizontalalignment='center', size='small',
  60. transform=ax1.transAxes)
  61. # Set the right-hand Y-axis ticks and labels
  62. ax2 = ax1.twinx()
  63. scoreLabels = [format_score(scores[k].score, k) for k in testNames]
  64. # set the tick locations
  65. ax2.set_yticks(pos)
  66. # make sure that the limits are set equally on both yaxis so the
  67. # ticks line up
  68. ax2.set_ylim(ax1.get_ylim())
  69. # set the tick labels
  70. ax2.set_yticklabels(scoreLabels)
  71. ax2.set_ylabel('Test Scores')
  72. ax2.set_xlabel(('Percentile Ranking Across '
  73. '{grade} Grade {gender}s').format(
  74. grade=attach_ordinal(student.grade),
  75. gender=student.gender.title()))
  76. rect_labels = []
  77. # Lastly, write in the ranking inside each bar to aid in interpretation
  78. for rect in rects:
  79. # Rectangle widths are already integer-valued but are floating
  80. # type, so it helps to remove the trailing decimal point and 0 by
  81. # converting width to int type
  82. width = int(rect.get_width())
  83. rankStr = attach_ordinal(width)
  84. # The bars aren't wide enough to print the ranking inside
  85. if width < 5:
  86. # Shift the text to the right side of the right edge
  87. xloc = width + 1
  88. # Black against white background
  89. clr = 'black'
  90. align = 'left'
  91. else:
  92. # Shift the text to the left side of the right edge
  93. xloc = 0.98*width
  94. # White on magenta
  95. clr = 'white'
  96. align = 'right'
  97. # Center the text vertically in the bar
  98. yloc = rect.get_y() + rect.get_height()/2.0
  99. label = ax1.text(xloc, yloc, rankStr, horizontalalignment=align,
  100. verticalalignment='center', color=clr, weight='bold',
  101. clip_on=True)
  102. rect_labels.append(label)
  103. # make the interactive mouse over give the bar title
  104. ax2.fmt_ydata = format_ycursor
  105. # return all of the artists created
  106. return {'fig': fig,
  107. 'ax': ax1,
  108. 'ax_right': ax2,
  109. 'bars': rects,
  110. 'perc_labels': rect_labels,
  111. 'cohort_label': cohort_label}
  112. student = Student('Johnny Doe', 2, 'boy')
  113. scores = dict(zip(testNames,
  114. (Score(v, p) for v, p in
  115. zip(['7', '48', '12:52', '17', '14'],
  116. np.round(np.random.uniform(0, 1,
  117. len(testNames))*100, 0)))))
  118. cohort_size = 62 # The number of other 2nd grade boys
  119. arts = plot_student_results(student, scores, cohort_size)
  120. plt.show()

条形图演示2

下载这个示例