如何使用 matplotlib 模拟 plt.hist 绘制 np.histogram 的结果

Dom*_*ise 11 python numpy matplotlib

我喜欢这样绘制直方图:

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')
Run Code Online (Sandbox Code Playgroud)

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

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]
Run Code Online (Sandbox Code Playgroud)

但问题始终是,“我如何H再次绘制它,使其看起来就像以前的 matplotlib 版本。

我想出的解决方案如下所示:

plt.plot(bins, np.insert(H, 0, H[0]), '-', drawstyle='steps')
Run Code Online (Sandbox Code Playgroud)

绘制直方图的两种不同版本。

但是,看起来结果并不相同,创建H用于绘制它的副本的感觉也不是很好。

我缺少一些优雅的解决方案吗?(我还没有尝试使用plt.bar,因为当想要比较直方图时,条形图不能很好地工作)

tmd*_*son 8

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

一种方法是使用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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

另一种选择是plt.step

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()
Run Code Online (Sandbox Code Playgroud)

边缘并没有完全延伸,因此如果这对您来说是一个大问题,您可能需要在任一端添加一个 0-bin

在此处输入图片说明

  • 我从来没有说过不要使用 np.histogram。事实上我的两个解决方案都使用它。所以不确定你的评论是什么意思。 (2认同)