python绘制给定binned的简单直方图

2024-06-16 14:55:07 发布

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

我有计数数据(100个),每个对应一个箱子(0到99)。我需要把这些数据绘制成直方图。但是,柱状图计算这些数据并不能正确绘制,因为我的数据已经被装箱。

import random
import matplotlib.pyplot as plt
x = random.sample(range(1000), 100)
xbins = [0, len(x)]
#plt.hist(x, bins=xbins, color = 'blue') 
#Does not make the histogram correct. It counts the occurances of the individual counts. 

plt.plot(x)
#plot works but I need this in histogram format
plt.show()

Tags: the数据importplot绘制pltrandom直方图
3条回答

问题出在你的xbins上。你现在有

xbins = [0, len(x)]

这会给你列表[0,100]。这意味着您将只看到1个bin(而不是2个)被0限制在0之下,而被100限制在100之上。我不完全确定你想从你的直方图中得到什么。如果你想要两个间隔不均的箱子,你可以使用

xbins = [0, 100, 1000]

把100以下的东西放在一个箱子里,其他的都放在另一个箱子里。另一个选择是使用整数值来获得一定数量的均匀间隔的容器。换句话说就是

plt.hist(x, bins=50, color='blue')

其中bins是所需的bin数。

另一方面,每当我不记得如何使用matplotlib时,我通常都会去thumbnail gallery找到一个例子,看起来或多或少是我想要完成的。这些示例都有附带的源代码,因此非常有用。matplotlib的documentation也非常方便。

酷,谢谢!我想手术室想做的是:

import random
import matplotlib.pyplot as plt
x=[x/1000 for x in random.sample(range(100000),100)]
xbins=range(0,len(x))
plt.hist(x, bins=xbins, color='blue')
plt.show()

如果我理解你想要正确实现的目标,那么下面的内容应该是你想要的:

import matplotlib.pyplot as plt
plt.bar(range(0,100), x)
plt.show()

它不使用hist(),但看起来您已经将数据放入了容器中,因此不需要。

相关问题 更多 >