用matplotlib绘制带有频率和计数的直方图

5

我有一些数据(来自一个包含两列的空格分隔文本文件),这些数据已经被分组,但每组仅有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
2个回答

1

如果你在使用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()

请不要使用 pylab,而是使用 import matplotlib.pyplot as plt 进行绘图,使用 import numpy as np 进行数学计算。 - tacaswell
@tcaswell,为什么?pylab有什么问题吗?我得到了相同的结果。 - Akavall
1
因为它可以批量导入各种东西。如果周围没有那么多示例,我们就会弃用它。 - tacaswell
它也极大地混淆了函数的来源。MPL收到了一些本应该发送给NumPy的错误报告。 - tacaswell
谢谢! :) 让互联网变得更加准确。 - tacaswell

1
我不是matplotlib的专家,但我发现hist非常有用。matplotlib网站上的示例很好地概述了一些功能。
我不知道如何使用您提供的示例数据而不进行转换。在创建直方图之前,我修改了您的示例以去量化那些数据。
我使用这个问题的第一个答案计算了bin大小。
import matplotlib.pyplot as plt
import numpy as np

data = np.loadtxt('file.txt')
dequantized = data[:,0].repeat(data[:,1].astype(int))

dequantized[0:7]
# Each row's first column is repeated the number of times found in the
# second column creating a single array.
# array([ 264.,  265.,  266.,  266.,  266.,  266.,  267.])

def bins(xmin, xmax, binwidth, padding):
    # Returns an array of integers which can be used to represent bins
    return np.arange(
        xmin - (xmin % binwidth) - padding,
        xmax + binwidth + padding,
        binwidth)

histbins = bins(min(dequantized), max(dequantized), 5, 5)
plt.figure(1)
plt.hist(dequantized, histbins)
plt.show()

这个直方图的显示如下所示。 带有5个bin宽度的直方图

我希望这个例子对你有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接