带频率和计数的matplotlib直方图

2024-06-16 10:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有数据(来自一个有两列的空格分隔的文本文件),它已经被装箱,但是只有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

Tags: 数据numpytxtdata宽度matplotlib绘制bar
2条回答

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

我不是matplotlib的专家,但我发现hist非常有用。matplotlib site上的示例对一些特性进行了很好的概述。

我不知道如何使用您提供的示例数据而不转换它。我修改了您的示例,在创建直方图之前对这些数据进行去量化。

我用this question's first answer计算了箱子的大小。

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()

显示的直方图如下所示。 Histogram with a binwidth of 5

我希望这个例子有用。

相关问题 更多 >