Python数据可视化第7讲:matplotlib绘制直⽅图函数hist
1. hist 函数介绍
芋头的做法hist 函数⽤于绘制直⽅图,直⽅图本质上是⼀种统计图。hist 函数绘图数据由参数 x 提供,参数 x 提供多个数据,作为具有潜在不同长度的数据集列表([x0,x1,…]),也可以作为每个列都是数据集的⼆维数组。函数的调⽤格式如下:
hist(x, bins,**kwargs)
hist(x)
主要参数说明:
x:数组或序列输⼊值,必须参数,它接受⼀个数组或⼀系列不需要具有相同长度的数组。
bins:整数或序列或字符串,可选参数。如果 bins 是整数,则定义范围内等宽箱⼦(直⽅图块)的数量;如果 bins 是⼀个序列,它定义箱⼦边缘,包括第⼀个箱⼦的左边缘和最后⼀个箱⼦的右边缘;在这种情况下,箱⼦的间距可能不相等。除了最后⼀个(最右边的)箱⼦是半开的。举个例⼦,如果 bins 是:[1, 2, 3, 4],那么第⼀个箱⼦是 [1,2(包括1,但不包括2),第⼆个箱⼦是[2,3);然⽽,最后⼀个箱⼦是[3,4],其中包括4。
2. hist 函数绘图⽰例
2.1 绘制⼀个简单的直⽅图床垫一般多厚
绘制⼀个简单的直⽅图。代码如下,数据集 x 提供绘图数据,bins=6 表⽰绘制的直⽅图块为 6 个,也就是将 x 提供的数据划分为 6 个区间进⾏分别统计,即分别统计数据集 x 中的数据落在区间 [1,1.5)、[1.5,2.0)、[2.0,2.5)、…、[3.5,4] 这 6 个区间的数量。直⽅图的⾼度就是落在对应区间的数据个数。
import matplotlib.pyplot as plt
# step1:准备画图的数据
x =[1,2,3,4,1,2,3,4,3,2,4,2,1,4,3,2,2,2,2,3,3,2,3,4,2,2,2]
# step2:⼿动创建⼀个figure对象,相当于⼀个空⽩的画布
figure = plt.figure()
降血糖的药物# step3:在画布上添加1个⼦块,标定绘图位置
axes1 = plt.subplot(1,1,1)
# step4:绘制直⽅图
axes1.hist(x, bins=6)一生一世酒色
axes1.t_title('a simple histogram')
# step5:展⽰
plt.show()
上⾯代码的运⾏结果:很明显,落在区间[2.0,2.5) 的数据是最多的。
2.2 通过numpy⽣成数据绘制⼀个直⽅图
通过 numpy ⽣成数据绘制⼀个直⽅图,代码如下:
import matplotlib.pyplot as plt
import numpy as np
# step1:准备画图的数据
N_points =100000
n_bins =20
x = np.random.randn(N_points)
# step2:⼿动创建⼀个figure对象,相当于⼀个空⽩的画布
figure = plt.figure()
axes1 = plt.subplot(1,1,1)
# step4:绘制直⽅图
axes1.hist(x, bins=n_bins)
axes1.t_title('a simple histogram')
# step5:展⽰
plt.show()
上⾯代码的运⾏结果:
2.3 绘制具有多个数据集的直⽅图
绘制具有多个数据集的直⽅图,并设置基本属性,代码⽰例如下:
np.random.ed(19680801)
n_bins =10
x = np.random.randn(1000,3)
colors =['red','tan','lime']
# step2:⼿动创建⼀个figure对象,相当于⼀个空⽩的画布
figure = plt.figure()
axes1 = plt.subplot(1,1,1)
# step4:绘制直⽅图
axes1.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
axes1.t_title('a simple histogram')
axes1.legend()
# step5:展⽰
plt.show()
上⾯代码的运⾏结果:
2.4 直⽅图与拟合曲线
在绘制直⽅图的基础上,绘制⼀条拟合曲线,代码如下:
mu =100# mean of distribution
sigma =15# standard deviation of distribution
x = mu + sigma * np.random.randn(437)
num_bins =50
# step2:⼿动创建⼀个figure对象,相当于⼀个空⽩的画布
figure = plt.figure()高乾
ps移动工具
axes1 = plt.subplot(1,1,1)
# step4:绘制直⽅图
n, bins, patches = axes1.hist(x, num_bins, density=1)
# step5:绘制⼀条拟合曲线
辞职离别感言简短y =((1/(np.sqrt(2* np.pi)* sigma))*
办公室装修方案
axes1.plot(bins, y,'--')
# step6:设置基本元素
axes1.t_xlabel('Smarts')
axes1.t_ylabel('Probability density')
axes1.t_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
# step7:展⽰
plt.show()
上⾯代码的运⾏结果: