我有数据(来自一个以空格分隔的两列文本文件),这些数据已经分箱,但宽度仅为 1。我想将此宽度增加到大约 5。如何在 Python 中使用 numpy/matplotlib 执行此操作?
使用,
data = loadtxt('file.txt')
x = data[:, 0]
y = data[:, 1]
plt.bar(x,y)
创建了太多条并使用,
plt.hist(data)
未正确绘制直方图。我想我不明白 matplotlib 的直方图绘图是如何工作的。
查看下面的一些数据。
264 1
265 1
266 4
267 2
268 2
269 2
270 2
271 2
272 5
273 3
274 2
275 6
276 7
277 3
278 7
279 5
280 9
281 4
282 8
283 11
284 9
285 15
286 19
287 11
288 12
289 10
290 13
291 18
292 20
293 14
294 15
最佳答案
如果您在使用plt.bar
之前使用numpy.reshape
来转换您的数据会怎么样,例如:
In [83]: import numpy as np
In [84]: import matplotlib.pyplot as plt
In [85]: data = np.array([[1,2,3,4,5,6], [4,3,8,9,1,2]]).T
In [86]: data
Out[86]:
array([[1, 4],
[2, 3],
[3, 8],
[4, 9],
[5, 1],
[6, 2]])
In [87]: y = data[:,1].reshape(-1,2).sum(axis=1)
In [89]: y
Out[89]: array([ 7, 17, 3])
In [91]: x = data[:,0].reshape(-1,2).mean(axis=1)
In [92]: x
Out[92]: array([ 1.5, 3.5, 5.5])
In [96]: plt.bar(x, y)
Out[96]: <Container object of 3 artists>
In [97]: plt.show()
关于python - 具有频率和计数的 matplotlib 直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709564/