python:绘制直方图(Histogram)

简介

本文主要总结如何绘制直方图,以及常用的使用场景。

什么是直方图:一个随机变量在各个取值区间有个概率分布,将其绘制出来:x轴为等间隔的取值区间(bins),y轴为该区间的频数(可归一化),即直方图。

接口

Signature:
plt.hist(
    x,
    bins=None,
    range=None,
    density=None,
    weights=None,
    cumulative=False,
    bottom=None,
    histtype='bar',
    align='mid',
    orientation='vertical',
    rwidth=None,
    log=False,
    color=None,
    label=None,
    stacked=False,
    normed=None,
    *,
    data=None,
    **kwargs,
)
Docstring:
Plot a histogram.

Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.

实例1:正态分布的直方图

实例
生成一个正态分布数据x,然后绘制其直方图。
代码

mu,sigma = 0,1
x = np.random.normal(mu,sigma,size=5000)
n, bins,patches = plt.hist(x,bins=20)
print('n:',n)
print('bins:',bins)
print('patches:',patches)

分析
输入参数:

  • x:即随机变量的取值数据
  • bins:表示将x等间隔分成多少个区间。比如这里分成了20个区间,具体说:它是将[min(x),max(x)]这个范围等间隔分成20个区间(bin),即有21个区间端点。

返回参数:

  • n:各区间(bin)的频数,即20个柱子的高度,
  • bins:21个区间端点。查看数值可以看到第一个端点为min(x),最后一个端点为max(x)。
  • patches:表示20个柱子

结果

n: [  2.   1.  22.  36.  81. 161. 329. 448. 580. 703. 745. 590. 507. 354.
 217. 115.  73.  25.  10.   1.]
bins: [-3.66700533 -3.30660994 -2.94621455 -2.58581916 -2.22542377 -1.86502838
 -1.50463298 -1.14423759 -0.7838422  -0.42344681 -0.06305142  0.29734397
  0.65773937  1.01813476  1.37853015  1.73892554  2.09932093  2.45971632
  2.82011172  3.18050711  3.5409025 ]
patches: <a list of 20 Patch objects>

在这里插入图片描述

拓展
使用其他输入参数,可以改进直方图。常用的有:

1、指定分隔范围:range
使用场景:1.想让区间数据更清晰;2.扔掉一些区间外的‘坏点’

n, bins,patches = plt.hist(x,bins=20,range=(-3,3))
print(‘bins:’,bins)

结果:

bins: [-3.  -2.7 -2.4 -2.1 -1.8 -1.5 -1.2 -0.9 -0.6 -0.3  0.   0.3  0.6  0.9
  1.2  1.5  1.8  2.1  2.4  2.7  3. ]

在这里插入图片描述

2、将频数归一化为概率密度:density
纵轴默认为频数,可归一化为概率密度。即归一化后,所有柱子的面积之和为1,即某区间的概率密度=频数/总数/区间长度,可理解为该区间的平均概率密度(或该区间的中值点的概率密度)
预期结果:归一化后的概率密度与标准的正态分布函数(概率密度函数)是吻合的。

_ ,ax = plt.subplots()
n, bins,patches = ax.hist(x,bins=20,range=(-3,3),density=True)
# 验证正态分布
y1 = scipy.stats.norm.pdf(bins, loc=mu, scale=sigma)
#y2 = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2))
ax.plot(bins,y1,'r--')

结果:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章