样式表参考

此脚本演示了一组常见示例图上的不同可用样式表:散点图,图像,条形图,面片,线图和直方图,

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

样式表参考示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Fixing random state for reproducibility
  4. np.random.seed(19680801)
  5. def plot_scatter(ax, prng, nb_samples=100):
  6. """Scatter plot.
  7. """
  8. for mu, sigma, marker in [(-.5, 0.75, 'o'), (0.75, 1., 's')]:
  9. x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples))
  10. ax.plot(x, y, ls='none', marker=marker)
  11. ax.set_xlabel('X-label')
  12. return ax
  13. def plot_colored_sinusoidal_lines(ax):
  14. """Plot sinusoidal lines with colors following the style color cycle.
  15. """
  16. L = 2 * np.pi
  17. x = np.linspace(0, L)
  18. nb_colors = len(plt.rcParams['axes.prop_cycle'])
  19. shift = np.linspace(0, L, nb_colors, endpoint=False)
  20. for s in shift:
  21. ax.plot(x, np.sin(x + s), '-')
  22. ax.set_xlim([x[0], x[-1]])
  23. return ax
  24. def plot_bar_graphs(ax, prng, min_value=5, max_value=25, nb_samples=5):
  25. """Plot two bar graphs side by side, with letters as x-tick labels.
  26. """
  27. x = np.arange(nb_samples)
  28. ya, yb = prng.randint(min_value, max_value, size=(2, nb_samples))
  29. width = 0.25
  30. ax.bar(x, ya, width)
  31. ax.bar(x + width, yb, width, color='C2')
  32. ax.set_xticks(x + width)
  33. ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
  34. return ax
  35. def plot_colored_circles(ax, prng, nb_samples=15):
  36. """Plot circle patches.
  37. NB: draws a fixed amount of samples, rather than using the length of
  38. the color cycle, because different styles may have different numbers
  39. of colors.
  40. """
  41. for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'], range(nb_samples)):
  42. ax.add_patch(plt.Circle(prng.normal(scale=3, size=2),
  43. radius=1.0, color=sty_dict['color']))
  44. # Force the limits to be the same across the styles (because different
  45. # styles may have different numbers of available colors).
  46. ax.set_xlim([-4, 8])
  47. ax.set_ylim([-5, 6])
  48. ax.set_aspect('equal', adjustable='box') # to plot circles as circles
  49. return ax
  50. def plot_image_and_patch(ax, prng, size=(20, 20)):
  51. """Plot an image with random values and superimpose a circular patch.
  52. """
  53. values = prng.random_sample(size=size)
  54. ax.imshow(values, interpolation='none')
  55. c = plt.Circle((5, 5), radius=5, label='patch')
  56. ax.add_patch(c)
  57. # Remove ticks
  58. ax.set_xticks([])
  59. ax.set_yticks([])
  60. def plot_histograms(ax, prng, nb_samples=10000):
  61. """Plot 4 histograms and a text annotation.
  62. """
  63. params = ((10, 10), (4, 12), (50, 12), (6, 55))
  64. for a, b in params:
  65. values = prng.beta(a, b, size=nb_samples)
  66. ax.hist(values, histtype="stepfilled", bins=30,
  67. alpha=0.8, density=True)
  68. # Add a small annotation.
  69. ax.annotate('Annotation', xy=(0.25, 4.25), xycoords='data',
  70. xytext=(0.9, 0.9), textcoords='axes fraction',
  71. va="top", ha="right",
  72. bbox=dict(boxstyle="round", alpha=0.2),
  73. arrowprops=dict(
  74. arrowstyle="->",
  75. connectionstyle="angle,angleA=-95,angleB=35,rad=10"),
  76. )
  77. return ax
  78. def plot_figure(style_label=""):
  79. """Setup and plot the demonstration figure with a given style.
  80. """
  81. # Use a dedicated RandomState instance to draw the same "random" values
  82. # across the different figures.
  83. prng = np.random.RandomState(96917002)
  84. # Tweak the figure size to be better suited for a row of numerous plots:
  85. # double the width and halve the height. NB: use relative changes because
  86. # some styles may have a figure size different from the default one.
  87. (fig_width, fig_height) = plt.rcParams['figure.figsize']
  88. fig_size = [fig_width * 2, fig_height / 2]
  89. fig, axes = plt.subplots(ncols=6, nrows=1, num=style_label,
  90. figsize=fig_size, squeeze=True)
  91. axes[0].set_ylabel(style_label)
  92. plot_scatter(axes[0], prng)
  93. plot_image_and_patch(axes[1], prng)
  94. plot_bar_graphs(axes[2], prng)
  95. plot_colored_circles(axes[3], prng)
  96. plot_colored_sinusoidal_lines(axes[4])
  97. plot_histograms(axes[5], prng)
  98. fig.tight_layout()
  99. return fig
  100. if __name__ == "__main__":
  101. # Setup a list of all available styles, in alphabetical order but
  102. # the `default` and `classic` ones, which will be forced resp. in
  103. # first and second position.
  104. style_list = ['default', 'classic'] + sorted(
  105. style for style in plt.style.available if style != 'classic')
  106. # Plot a demonstration figure for every available style sheet.
  107. for style_label in style_list:
  108. with plt.style.context(style_label):
  109. fig = plot_figure(style_label=style_label)
  110. plt.show()

脚本的总运行时间:(0分5.216秒)

下载这个示例