用matplotlib模拟plt.his绘制np.histogram结果

2024-04-26 14:41:23 发布

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

我喜欢这样绘制直方图:

data = [-0.5, 0.5, 0.5, 0.5, 
    1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2]

plt.hist(data, bins=5, range=[-1, 4], histtype='step')

现在,当我有大的输入数据(大于我的内存)时,我需要逐块填充直方图。E、 g.像这样:

H, bins = np.histogram([], bins=5, range=[-1, 4])
for data in a_lot_of_input_files:
    H += np.histogram(data, bins=5, range=[-1, 4])[0]

但问题总是,“我如何再次绘制这个H,所以它看起来就像以前的matplotlib版本。

我想出的解决方案是这样的:

plt.plot(bins, np.insert(H, 0, H[0]), '-', drawstyle='steps')

Two different versions of plotting a histogram.

但是,结果看起来既不相同,也不觉得创建一个H的副本来绘制它很好。

有没有什么优雅的解决方案我错过了?(我还没有尝试使用plt.bar,因为当人们想要比较直方图时,条形图不能很好地工作)


Tags: 数据内存fordatastepnp绘制range
1条回答
网友
1楼 · 发布于 2024-04-26 14:41:23

不知道你所说的“条形图不能很好地工作,当人们想要比较直方图时”

一种方法是使用plt.bar

import matplotlib.pyplot as plt
import numpy as np

data = [-0.5, 0.5, 0.5, 0.5, 
    1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2]

plt.hist(data, bins=5, range=[-1, 4], histtype='step',edgecolor='r',linewidth=3)
H, bins = np.histogram(data[:6], bins=5, range=[-1, 4])
H+=np.histogram(data[6:], bins=5,range=[-1, 4])[0]

plt.bar(bins[:-1],H,width=1)

plt.show()

enter image description here

另一种选择是^{}

import matplotlib.pyplot as plt
import numpy as np

data = [-0.5, 0.5, 0.5, 0.5, 
    1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2]

plt.hist(data, bins=5, range=[-1, 4], histtype='step',edgecolor='r')
H, bins = np.histogram(data[:6], bins=5, range=[-1, 4])
H+=np.histogram(data[6:], bins=5,range=[-1, 4])[0]

bincentres = [(bins[i]+bins[i+1])/2. for i in range(len(bins)-1)]
plt.step(bincentres,H,where='mid',color='b',linestyle='--')

plt.ylim(0,6)

plt.show()

边缘不会一直延伸,因此如果这对您来说是个大问题,您可能需要在两端添加一个0-bin

enter image description here

相关问题 更多 >