如何在 Python 中使用 Matplotlib 绘制带有数据列表的直方图?

新手上路,请多包涵
阅读 328
1 个回答

如果您想要直方图,则不需要将任何“名称”附加到 x 值,因为:

  • x 轴上,您将拥有数据箱
  • y 轴计数(默认情况下)或频率( density=True
 import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

np.random.seed(42)
x = np.random.normal(size=1000)

plt.hist(x, density=True, bins=30)  # density=False would make counts
plt.ylabel('Probability')
plt.xlabel('Data');

在此处输入图像描述

请注意, bins=30 的数量是任意选择的,并且有 Freedman–Diaconis 规则可以更科学地选择“正确”的 bin 宽度:

[![在此处输入图片描述](https://i.stack.imgur.com/sVlfg.png) ,其中 IQR四分位距n 是要绘制的数据点总数

因此,根据这一规则,可以计算出 bins 的数量:

 q25, q75 = np.percentile(x, [25, 75])
bin_width = 2 * (q75 - q25) * len(x) ** (-1/3)
bins = round((x.max() - x.min()) / bin_width)
print("Freedman–Diaconis number of bins:", bins)
plt.hist(x, bins=bins);


 Freedman–Diaconis number of bins: 82

在此处输入图像描述

最后,您可以使用 PDF 行、标题和图例使您的直方图更漂亮:

 import scipy.stats as st

plt.hist(x, density=True, bins=82, label="Data")
mn, mx = plt.xlim()
plt.xlim(mn, mx)
kde_xs = np.linspace(mn, mx, 300)
kde = st.gaussian_kde(x)
plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
plt.legend(loc="upper left")
plt.ylabel("Probability")
plt.xlabel("Data")
plt.title("Histogram");

在此处输入图像描述

如果您愿意探索其他机会,可以使用快捷方式 seaborn

 # !pip install seaborn
import seaborn as sns
sns.displot(x, bins=82, kde=True);

在此处输入图像描述

现在回到OP。

如果您的数据点数量有限,则条形图更适合表示您的数据。然后您可以将标签附加到 x 轴:

 x = np.arange(3)
plt.bar(x, height=[1,2,3])
plt.xticks(x, ['a','b','c']);

在此处输入图像描述

原文由 Sergey Bushmanov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题