我有大量数据文件,因此使用 numpy 直方图(与 matplotlib 中使用的相同)手动生成直方图并更新它们。然而,在绘图时,我感觉图表发生了变化。
这是我用来批量手动创建和更新直方图的代码。请注意,所有直方图共享相同的箱。
temp = np.histogram(batch, bins=np.linspace(0, 40, 41))
hist += temp[0]
当我解析数据文件时,会重复上面的代码。例如,一个小数据集将具有以下作为最终直方图数据:
[8190, 666, 278, 145, 113, 83, 52, 48, 45, 44, 45, 29, 28, 45, 29, 15, 16, 10, 17, 7, 15, 6, 10, 7, 3, 5, 7, 4, 2, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 29]
下面是绘图代码。
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
plt.xticks(np.linspace(0, 1, 11))
plt.hist([i/40 for i in range(40)], bins=np.linspace(0, 1, 41), weights=scores, rwidth=0.7)
plt.yscale('log', nonposy='clip')
由此产生的数字非常奇怪。它在 [0.475, 0.5) 处没有显示柱,我预计范围 [0.975, 1.0] 的 0.975 bin 包含最后 29 个值。然而,我看到该柱位于 [0.950, 0.975) 位置。我认为这可能与使用 bin 和 linspace 有关,但诱饵数组的大小和权重是相同的。
我从未见过这种行为。我还认为这将是范围 [ x, x+width) 的方式,但我对此没有遇到任何问题。
使用 linspace 的注意事项。它指定边缘,因此 40 个 bin 由 41 个边缘指定。
In [2]: np.linspace(0,1,41)
Out[2]:
array([0. , 0.025, 0.05 , 0.075, 0.1 , 0.125, 0.15 , 0.175, 0.2 ,
0.225, 0.25 , 0.275, 0.3 , 0.325, 0.35 , 0.375, 0.4 , 0.425,
0.45 , 0.475, 0.5 , 0.525, 0.55 , 0.575, 0.6 , 0.625, 0.65 ,
0.675, 0.7 , 0.725, 0.75 , 0.775, 0.8 , 0.825, 0.85 , 0.875,
0.9 , 0.925, 0.95 , 0.975, 1. ])
In [3]: len(np.linspace(0,1,41))
Out[3]: 41