所以我有个小问题。我在scipy中有一个已经是直方图格式的数据集,所以我有存储箱的中心和每个存储箱的事件数量。我现在怎么能把它画成直方图。我试着去做
bins, n=hist()但它不喜欢这样。有什么建议吗?
发布于 2011-03-17 00:46:20
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()

面向对象的接口也很简单:
fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")如果您使用的是自定义(非常数)箱,则可以使用np.diff计算宽度,将宽度传递给ax.bar并使用ax.set_xticks标记箱边缘:
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()

发布于 2013-09-04 18:15:41
如果你不想要条形图,你可以这样画它:
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins, edges = np.histogram(x, 50, normed=1)
left,right = edges[:-1],edges[1:]
X = np.array([left,right]).T.flatten()
Y = np.array([bins,bins]).T.flatten()
plt.plot(X,Y)
plt.show()

发布于 2017-05-06 23:55:54
我知道这没有回答您的问题,但是当我搜索直方图的matplotlib解决方案时,我总是会出现在这个页面上,因为简单的histogram_demo已经从matplotlib示例图库页面中删除了。
这是一个不需要导入numpy的解决方案。我只导入numpy来生成要绘制的数据x。它依赖于函数hist,而不是@unutbu的answer中的函数bar。
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

另外,还可以查看matplotlib gallery和matplotlib examples。
https://stackoverflow.com/questions/5328556
复制相似问题