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
,因为当想要比较直方图时,条形图不能很好地工作)
不知道你说的“条形图不能很好地工作,当人们想要比较直方图时”是什么意思,
一种方法是使用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
归档时间: |
|
查看次数: |
24244 次 |
最近记录: |