python - 直方图 Matplotlib

标签 python numpy matplotlib scipy histogram

所以我有一个小问题。我有一个 scipy 数据集,它已经是直方图格式,所以我有 bin 的中心和每个 bin 的事件数。我现在如何绘制为直方图。我试着做

bins, n=hist()

但它不喜欢那样。有什么建议吗?

最佳答案

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

enter image description here

面向对象的接口(interface)也很简单:

fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

如果您使用自定义(非常量)bin,您可以使用 np.diff 传递计算宽度,将宽度传递给 ax.bar 并使用 ax.set_xticks 标记 bin 边缘:

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
hist, bins = np.histogram(x, bins=bins)
width = np.diff(bins)
center = (bins[:-1] + bins[1:]) / 2

fig, ax = plt.subplots(figsize=(8,3))
ax.bar(center, hist, align='center', width=width)
ax.set_xticks(bins)
fig.savefig("/tmp/out.png")

plt.show()

enter image description here

关于python - 直方图 Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5328556/

相关文章:

python - Numpy 随机函数为给定参数创建不一致的形状

Python/PyGame 从类/方法创建具有随机属性的随机怪物

python - CX-卡住 "ImportError: DLL load failed: %1 is not a valid Win32 application"

python - 如何以向量化方式修改具有任意索引的 numpy 数组?

python - Matplotlib:绘图函数 plt.contourf() 无法从颜色图 jet 绘制超过 9 种颜色

python - 如何在 Python 中更改目录?

python - 列为字典中的值,获取最长列表的键

python / NumPy : Divide array

python - Matplotlib - 在保持正确的 x 值的同时跳过 xticks

python - 未使用 Matplotlib 绘制线条/轨迹