直方图(hist)函数的几个特性演示

除基本直方图外,此演示还显示了一些可选功能:

  • 设置数据箱的数量。
  • 标准化标志,用于标准化箱高度,使直方图的积分为1.得到的直方图是概率密度函数的近似值。
  • 设置条形的面部颜色。
  • 设置不透明度(alpha值)。

选择不同的存储量和大小会显著影响直方图的形状。Astropy文档有很多关于如何选择这些参数的部分。

  1. import matplotlib
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. np.random.seed(19680801)
  5. # example data
  6. mu = 100 # mean of distribution
  7. sigma = 15 # standard deviation of distribution
  8. x = mu + sigma * np.random.randn(437)
  9. num_bins = 50
  10. fig, ax = plt.subplots()
  11. # the histogram of the data
  12. n, bins, patches = ax.hist(x, num_bins, density=1)
  13. # add a 'best fit' line
  14. y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
  15. np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
  16. ax.plot(bins, y, '--')
  17. ax.set_xlabel('Smarts')
  18. ax.set_ylabel('Probability density')
  19. ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
  20. # Tweak spacing to prevent clipping of ylabel
  21. fig.tight_layout()
  22. plt.show()

直方图特性演示

参考

此示例显示了以下函数和方法的使用:

  1. matplotlib.axes.Axes.hist
  2. matplotlib.axes.Axes.set_title
  3. matplotlib.axes.Axes.set_xlabel
  4. matplotlib.axes.Axes.set_ylabel

下载这个示例