使用 plt.hist() 绘制直方图

数据挖掘 Python 直方图 matplotlib
2021-10-08 12:04:26

我是 Python 新手,想绘制一个介于 -0.2 和 0.2 之间的值列表。列表看起来像这样

[...-0.01501152092971969,
  -0.01501152092971969,
  -0.01501152092971969,
  -0.01501152092971969,
  -0.01501152092971969,
  -0.01501152092971969,
  -0.01501152092971969,
  -0.01501152092971969,
  -0.01501152092971969,
  -0.01489985147131656,
  -0.015833709930856088,
  -0.015833709930856088,
  -0.015833709930856088,
  -0.015833709930856088,
  -0.015833709930856088...and so on].

在统计学中,我学会了将我的数据分组,以获得一个有用的直方图图,这取决于如此大的数据。

如何将 python 中的类添加到我的绘图中?

我的代码是

plt.hist(data)

直方图看起来像 在此处输入图像描述

但它应该看起来像 在此处输入图像描述

2个回答

您的直方图是有效的,但它有太多的 bin 无用。

如果您想要多个等间距的箱,您可以简单地通过bins参数传递该数字plt.hist,例如:

plt.hist(data, bins=10)

如果您希望您的垃圾箱具有特定的边缘,您可以将它们作为列表传递给bins

plt.hist(data, bins=[0, 5, 10, 15, 20, 25, 30, 35, 40, 60, 100])

最后,您还可以指定一种方法来自动计算 bin 边缘,例如auto(可用的方法在 的文档中numpy.histogram_bin_edges指定):

plt.hist(data, bins='auto')

完整的代码示例

import matplotlib.pyplot as plt
import numpy as np

# fix the random state for reproducibility
np.random.seed(19680801);

# sum of 2 normal distributions
n = 500;
data = 10 * np.random.randn(n) + 20 * np.random.randn(n) + 20;

# plot histograms with various bins
fig, axs = plt.subplots(1, 3, sharey=True, tight_layout=True, figsize=(9,3));
axs[0].hist(data, bins=10);
axs[1].hist(data, bins=[0, 5, 10, 15, 20, 25, 30, 35, 40, 60, 100]);
axs[2].hist(data, bins='auto');

在此处输入图像描述

如果我发现了问题,您必须指定垃圾箱大小。如此处所述

您可以给出一个包含 bin 边界的列表。

plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])

如果您只想让它们均匀分布,您可以简单地使用范围:

plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))

你也可以看看这里这里