数据界的搞笑担当?Matplotlib直方图绘制大揭秘,让你的数据也笑出腹肌!

在这里插入图片描述

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
学号分数
0A000176
1A000277
2A000378
3A000479
4A000580
.........
95A009683
96A009784
97A009885
98A009999
99A0100100

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()

在这里插入图片描述

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

腾飞开源

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值