mad*_*ast 101 python numpy matplotlib histogram scipy
所以我有一点问题.我有一个scipy的数据集已经是直方图格式,所以我有bin的中心和每个bin的事件数.我现在如何绘制直方图.我试着做
bins, n=hist()
Run Code Online (Sandbox Code Playgroud)
但它不喜欢那样.有什么建议?
unu*_*tbu 229
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()
Run Code Online (Sandbox Code Playgroud)

面向对象的接口也很简单:
fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")
Run Code Online (Sandbox Code Playgroud)
如果您使用自定义(非常量)分档,则可以使用计算宽度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()
Run Code Online (Sandbox Code Playgroud)
Mat*_*123 20
如果您不想要酒吧,可以像这样绘制:
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()
Run Code Online (Sandbox Code Playgroud)
tom*_*sen 12
我知道这不能回答你的问题,但是当我搜索直方图的matplotlib解决方案时,我总是在这个页面上结束,因为简单histogram_demo从matplotlib示例库页面中删除了.
这是一个解决方案,不需要numpy导入.我只导入numpy来生成x要绘制的数据.它依赖于函数hist而不是@unutbu 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')
Run Code Online (Sandbox Code Playgroud)
另请参阅matplotlib库和matplotlib示例.
Qui*_*2k1 10
我刚刚意识到该hist文档明确说明了当您已经拥有一个时该怎么做np.histogram
counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)
Run Code Online (Sandbox Code Playgroud)
这里重要的部分是您的计数只是权重。如果你这样做了,你就不再需要 bar 函数了
如果你愿意使用pandas:
pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')
Run Code Online (Sandbox Code Playgroud)
new plt.stairs(或ax.stairs) 直接与 一起使用np.histogram:
np.histogram返回计数和边缘plt.stairs接受计数和边缘例如,给定 unutbu 的样本x = 100 + 15 * np.random.randn(10000):
counts, edges = np.histogram(x, bins=50)
plt.stairs(counts, edges, fill=True)
Run Code Online (Sandbox Code Playgroud)
或者,np.histogram直接解压到plt.stairs:
plt.stairs(*np.histogram(x, bins=50), fill=True)
Run Code Online (Sandbox Code Playgroud)
有关如何使用楼梯图的更多示例,请参阅官方 matplotlib 库。