【发布时间】:2015-07-19 22:28:16
【问题描述】:
我有一个 100.000.000 个样本数据集,我想用 pyplot 制作一个直方图。但是阅读这个大文件会严重耗尽我的记忆(光标不再移动,...),所以我正在寻找“帮助”pyplot.hist 的方法。我在想将文件分成几个较小的文件可能会有所帮助。但我不知道之后如何组合它们。
【问题讨论】:
标签: python matplotlib
我有一个 100.000.000 个样本数据集,我想用 pyplot 制作一个直方图。但是阅读这个大文件会严重耗尽我的记忆(光标不再移动,...),所以我正在寻找“帮助”pyplot.hist 的方法。我在想将文件分成几个较小的文件可能会有所帮助。但我不知道之后如何组合它们。
【问题讨论】:
标签: python matplotlib
你可以合并pyplot.hist 的输出,或者像@titusjan 建议的numpy.histogram 那样,只要你每次调用它时保持你的垃圾箱是固定的。例如:
import matplotlib.pyplot as plt
import numpy as np
# Generate some fake data
data=np.random.rand(1000)
# The fixed bins (change depending on your data)
bins=np.arange(0,1.1,0.1)
sub_hist = [], []
# Split into 10 sub histograms
for i in np.arange(0,1000,10):
sub_hist_temp, bins_out = np.histogram(data[i:i+10],bins=bins)
sub_hist.append(sub_hist_temp)
# Sum the histograms
hist_sum = np.array(sub_hist).sum(axis=0)
# Plot the new summed data, using plt.bar
fig=plt.figure()
ax1=fig.add_subplot(211)
ax1.bar(bins[:-1],hist_sum,width=0.1) # Change width depending on your bins
# Plot the histogram of all data to check
ax2=fig.add_subplot(212)
hist_all, bins_out, patches = all=ax2.hist(data,bins=bins)
fig.savefig('histsplit.png')
【讨论】:
numpy.histogram 函数来计算子直方图,这样就不会进行不必要的绘图。只需将每次迭代的 bin 计数添加到总 bin 计数中即可。此外,您可以使用path.Path 类来绘制直方图,如果您有很多箱,这比条形图要快得多。见this example。