按性别分列的学士学位

包含多个时间序列的图形,其中演示了打印框架、刻度线和标签以及线图特性的广泛自定义样式。

还演示了文本标签沿右边缘的自定义放置,作为传统图例的替代方法。

按性别分列的学士学位示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.cbook import get_sample_data
  4. fname = get_sample_data('percent_bachelors_degrees_women_usa.csv',
  5. asfileobj=False)
  6. gender_degree_data = np.genfromtxt(fname, delimiter=',', names=True)
  7. # These are the colors that will be used in the plot
  8. color_sequence = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',
  9. '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5',
  10. '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f',
  11. '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']
  12. # You typically want your plot to be ~1.33x wider than tall. This plot
  13. # is a rare exception because of the number of lines being plotted on it.
  14. # Common sizes: (10, 7.5) and (12, 9)
  15. fig, ax = plt.subplots(1, 1, figsize=(12, 14))
  16. # Remove the plot frame lines. They are unnecessary here.
  17. ax.spines['top'].set_visible(False)
  18. ax.spines['bottom'].set_visible(False)
  19. ax.spines['right'].set_visible(False)
  20. ax.spines['left'].set_visible(False)
  21. # Ensure that the axis ticks only show up on the bottom and left of the plot.
  22. # Ticks on the right and top of the plot are generally unnecessary.
  23. ax.get_xaxis().tick_bottom()
  24. ax.get_yaxis().tick_left()
  25. fig.subplots_adjust(left=.06, right=.75, bottom=.02, top=.94)
  26. # Limit the range of the plot to only where the data is.
  27. # Avoid unnecessary whitespace.
  28. ax.set_xlim(1969.5, 2011.1)
  29. ax.set_ylim(-0.25, 90)
  30. # Make sure your axis ticks are large enough to be easily read.
  31. # You don't want your viewers squinting to read your plot.
  32. plt.xticks(range(1970, 2011, 10), fontsize=14)
  33. plt.yticks(range(0, 91, 10), fontsize=14)
  34. ax.xaxis.set_major_formatter(plt.FuncFormatter('{:.0f}'.format))
  35. ax.yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}%'.format))
  36. # Provide tick lines across the plot to help your viewers trace along
  37. # the axis ticks. Make sure that the lines are light and small so they
  38. # don't obscure the primary data lines.
  39. plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)
  40. # Remove the tick marks; they are unnecessary with the tick lines we just
  41. # plotted.
  42. plt.tick_params(axis='both', which='both', bottom=False, top=False,
  43. labelbottom=True, left=False, right=False, labelleft=True)
  44. # Now that the plot is prepared, it's time to actually plot the data!
  45. # Note that I plotted the majors in order of the highest % in the final year.
  46. majors = ['Health Professions', 'Public Administration', 'Education',
  47. 'Psychology', 'Foreign Languages', 'English',
  48. 'Communications\nand Journalism', 'Art and Performance', 'Biology',
  49. 'Agriculture', 'Social Sciences and History', 'Business',
  50. 'Math and Statistics', 'Architecture', 'Physical Sciences',
  51. 'Computer Science', 'Engineering']
  52. y_offsets = {'Foreign Languages': 0.5, 'English': -0.5,
  53. 'Communications\nand Journalism': 0.75,
  54. 'Art and Performance': -0.25, 'Agriculture': 1.25,
  55. 'Social Sciences and History': 0.25, 'Business': -0.75,
  56. 'Math and Statistics': 0.75, 'Architecture': -0.75,
  57. 'Computer Science': 0.75, 'Engineering': -0.25}
  58. for rank, column in enumerate(majors):
  59. # Plot each line separately with its own color.
  60. column_rec_name = column.replace('\n', '_').replace(' ', '_')
  61. line = plt.plot(gender_degree_data['Year'],
  62. gender_degree_data[column_rec_name],
  63. lw=2.5,
  64. color=color_sequence[rank])
  65. # Add a text label to the right end of every line. Most of the code below
  66. # is adding specific offsets y position because some labels overlapped.
  67. y_pos = gender_degree_data[column_rec_name][-1] - 0.5
  68. if column in y_offsets:
  69. y_pos += y_offsets[column]
  70. # Again, make sure that all labels are large enough to be easily read
  71. # by the viewer.
  72. plt.text(2011.5, y_pos, column, fontsize=14, color=color_sequence[rank])
  73. # Make the title big enough so it spans the entire plot, but don't make it
  74. # so big that it requires two lines to show.
  75. # Note that if the title is descriptive enough, it is unnecessary to include
  76. # axis labels; they are self-evident, in this plot's case.
  77. fig.suptitle('Percentage of Bachelor\'s degrees conferred to women in '
  78. 'the U.S.A. by major (1970-2011)\n', fontsize=18, ha='center')
  79. # Finally, save the figure as a PNG.
  80. # You can also save it as a PDF, JPEG, etc.
  81. # Just change the file extension in this call.
  82. # plt.savefig('percent-bachelors-degrees-women-usa.png', bbox_inches='tight')
  83. plt.show()

下载这个示例