首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >直方图Matplotlib

直方图Matplotlib
EN

Stack Overflow用户
提问于 2011-03-17 00:38:32
回答 7查看 173.4K关注 0票数 116

所以我有个小问题。我在scipy中有一个已经是直方图格式的数据集,所以我有存储箱的中心和每个存储箱的事件数量。我现在怎么能把它画成直方图。我试着去做

代码语言:javascript
复制
bins, n=hist()

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

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-03-17 00:46:20

代码语言:javascript
复制
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()

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

代码语言:javascript
复制
fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

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

代码语言:javascript
复制
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()

票数 255
EN

Stack Overflow用户

发布于 2013-09-04 18:15:41

如果你不想要条形图,你可以这样画它:

代码语言:javascript
复制
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()

票数 27
EN

Stack Overflow用户

发布于 2017-05-06 23:55:54

我知道这没有回答您的问题,但是当我搜索直方图的matplotlib解决方案时,我总是会出现在这个页面上,因为简单的histogram_demo已经从matplotlib示例图库页面中删除了。

这是一个不需要导入numpy的解决方案。我只导入numpy来生成要绘制的数据x。它依赖于函数hist,而不是@unutbu的answer中的函数bar

代码语言:javascript
复制
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 gallerymatplotlib examples

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5328556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档