带有自定义填充颜色的箱形图

此图说明了如何创建两种类型的箱形图(矩形和缺口),以及如何通过访问框图的艺术家属性来使用自定义颜色填充它们。 此外,labels参数用于为每个样本提供x-tick标签。

关于箱形图及其历史的一般参考可以在这里找到:http://vita.had.co.nz/papers/boxplots.pdf

自定义颜色箱形图示例

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # Random test data
  4. np.random.seed(19680801)
  5. all_data = [np.random.normal(0, std, size=100) for std in range(1, 4)]
  6. labels = ['x1', 'x2', 'x3']
  7. fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(9, 4))
  8. # rectangular box plot
  9. bplot1 = axes[0].boxplot(all_data,
  10. vert=True, # vertical box alignment
  11. patch_artist=True, # fill with color
  12. labels=labels) # will be used to label x-ticks
  13. axes[0].set_title('Rectangular box plot')
  14. # notch shape box plot
  15. bplot2 = axes[1].boxplot(all_data,
  16. notch=True, # notch shape
  17. vert=True, # vertical box alignment
  18. patch_artist=True, # fill with color
  19. labels=labels) # will be used to label x-ticks
  20. axes[1].set_title('Notched box plot')
  21. # fill with colors
  22. colors = ['pink', 'lightblue', 'lightgreen']
  23. for bplot in (bplot1, bplot2):
  24. for patch, color in zip(bplot['boxes'], colors):
  25. patch.set_facecolor(color)
  26. # adding horizontal grid lines
  27. for ax in axes:
  28. ax.yaxis.grid(True)
  29. ax.set_xlabel('Three separate samples')
  30. ax.set_ylabel('Observed values')
  31. plt.show()

下载这个示例