所以我有一个小问题。我有一个 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()
面向对象的接口(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()
关于python - 直方图 Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5328556/