1. 直方图介绍
- 直方图(Histogram),又称质量分布图,它是柱形图的一种,由一些列高度不等的纵向线段来表示数据分布的情况。直方图的横轴表示数据类型,纵轴表示分布情况。
- 直方图用于概率分布,它显示了一组数值序列在给定的数值范围内出现的概率或次数。
# 导包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 如果浏览器不显示图片,就需要加上这句话
%matplotlib inline
# 让图片中可以显示中文
plt.rcParams['font.sans-serif'] = "SimHei"
# 让图片中可以显示负号
plt.rcParams["axes.unicode_minus"] = False
# 支持svg矢量图
%config Inlinebackend.figure_format = "svg"
2. 绘制直方图
x = np.random.randint(0, 10, 100)
x
array([3, 1, 6, 8, 7, 5, 6, 7, 7, 0, 1, 4, 9, 5, 5, 5, 3, 2, 1, 4, 0, 8,
5, 3, 0, 9, 6, 1, 4, 6, 6, 0, 7, 7, 3, 9, 1, 1, 9, 7, 1, 1, 3, 1,
5, 7, 7, 0, 6, 3, 3, 0, 4, 8, 1, 2, 8, 9, 4, 6, 8, 8, 6, 5, 7, 6,
4, 8, 4, 2, 1, 8, 8, 0, 0, 5, 7, 7, 6, 3, 7, 8, 0, 6, 4, 8, 0, 4,
7, 9, 4, 0, 1, 0, 0, 7, 1, 2, 7, 3])
# 统计每个数出现的次数
pd.Series(x).value_counts()
7 15
1 13
0 13
6 11
8 11
4 10
3 9
5 8
9 6
2 4
Name: count, dtype: int64
# 直方图
plt.hist(x)
# 设置x轴的刻度
plt.xticks(range(10))
plt.show()
# bins:设置组数
plt.hist(x, bins=5)
# 设置x轴的刻度
plt.xticks(range(10))
plt.show()
# bins:自定义分组区间(左闭右开)
plt.hist(x, bins=[0, 2, 6, 9, 10])
# 设置x轴的刻度
plt.xticks(range(10))
plt.show()
3. Pandas获取Excel数据
df = pd.read_excel("06_hist.xlsx", sheet_name="hist")
df
学号 | 分数 | |
---|---|---|
0 | A0001 | 76 |
1 | A0002 | 77 |
2 | A0003 | 78 |
3 | A0004 | 79 |
4 | A0005 | 80 |
... | ... | ... |
95 | A0096 | 83 |
96 | A0097 | 84 |
97 | A0098 | 85 |
98 | A0099 | 99 |
99 | A0100 | 100 |
100 rows × 2 columns
x = df["分数"]
df.shape
(100, 2)
x.min(), x.max()
(76, 100)
# 统计每个数出现的次数
pd.Series(x).value_counts()
分数
84 9
85 9
82 9
83 9
80 7
81 7
89 4
87 4
86 4
88 4
99 3
92 3
91 3
90 3
100 3
93 2
94 2
76 2
98 2
97 2
96 2
77 2
79 2
78 2
95 1
Name: count, dtype: int64
# bins:自定义分组区间
# facecolor:设置柱背景色
# alpha:设置柱透明度
# edgecolor:设置柱边框颜色
plt.hist(x, bins=range(60, 111, 10), facecolor="b", alpha=0.5, edgecolor="k")
plt.show()
- 呈现概率分布
# density:呈现概率分布
plt.hist(x, bins=range(60, 111, 10), facecolor="b", alpha=0.5, edgecolor="k", density=True)
plt.show()