迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

如何在 Matplotlib 中绘制数据列表的直方图

作者:迹忆客 最近更新:2024/02/01 浏览次数:

我们可以使用 plt.hist() 方法从数据列表中绘制直方图。


plt.hist() 方法的语法

matplotlib.pyplot.hist(x,
                       bins=None,
                       range=None,
                       density=False,
                       weights=None,
                       cumulative=False,
                       bottom=None,
                       histtype='bar',
                       align='mid',
                       orientation='vertical',
                       rwidth=None,
                       log=False,
                       color=None,
                       label=None,
                       stacked=False, *,
                       data=None,
                       **kwargs)

示例:从数据列表中使用 Matplotlib 绘制直方图

import matplotlib.pyplot as plt

data = [3, 4, 2, 3, 4, 5, 4, 7, 8, 5, 4, 6, 2, 1, 0, 9, 7, 6, 6, 5, 4]

n, bins, patches = plt.hist(data)
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.title("Histogram")
plt.show()

在这里,我们在一个列表 data 中有数值。我们将这个列表传入 plt.hist() 命令,从值列表中生成一个直方图。plt.hist() 方法会返回二进制的频率、二进制的端点以及用于创建直方图的补丁列表。

在本例中,我们没有设置 bins 参数的值。默认情况下,bins 的值是 10,所以脚本会从 10 个 bins 的数据列表中创建直方图。

此外,我们可以在制作直方图时使用 bins 命令控制直方块的数量。

import matplotlib.pyplot as plt

data = [3, 4, 2, 3, 4, 5, 4, 7, 8, 5, 4, 6, 2, 1, 0, 9, 7, 6, 6, 5, 4]
n, bins, patches = plt.hist(data, bins=20)
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.title("Histogram with 20 bins")
plt.show()

这个过程显示了由 20 个直方块组成的直方图,这是平均划分整个列表值范围的结果。

默认情况下,density 参数的值被设置为 False;这意味着我们在直方图中得到每个 bin 的精确计数的图。如果我们想让列表中每个 bin 的概率密度图,我们需要将 density 设置为 True。如果 densityTrue,直方图下的区域积分为 1

import matplotlib.pyplot as plt

data = [3, 4, 2, 3, 4, 5, 4, 7, 8, 5, 4, 6, 2, 1, 0, 9, 7, 6, 6, 5, 4]
n, bins, patches = plt.hist(data, bins=20, density=True)
plt.xlabel("Weight")
plt.ylabel("Probability")
plt.title("Histogram with Probability Plot")
plt.show()

现在我们可以使用 color 参数设置直方图的颜色。

import matplotlib.pyplot as plt

data = [3, 4, 2, 3, 4, 5, 4, 7, 8, 5, 4, 6, 2, 1, 0, 9, 7, 6, 6, 5, 4]
n, bins, patches = plt.hist(data, bins=20, density=True, color="red")
plt.xlabel("Weight")
plt.ylabel("Probability")
plt.title("Red Histogram Plot")
plt.show()

此方法生成红色的直方图。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便