我想绘制几个直方图,但有时候的箱子比其他箱子大。我无法解释为什么我会得到这个...你可以在下面看到一个情节,红色的箱子比其他箱子宽。我的代码显示在图下面
import matplotlib as mpl
font = {'family':'serif','serif':'serif','weight':'normal','size':'18'}
mpl.rc('font',**font)
mpl.rc('text',usetex=True)
plt.close()
plt.subplots_adjust(left=0.15, bottom=0.15)
num_bins = 50
n, bins, patches = plt.hist(A, num_bins, facecolor='blue', alpha=0.5, label='Healthy SG')
n, bins, patches = plt.hist(B, num_bins, facecolor='red', alpha=0.5, label='Aged SG')
n, bins, patches = plt.hist(C, num_bins, facecolor='yellow', alpha=0.5, label='Healthy VG')
n, bins, patches = plt.hist(D, num_bins, facecolor='green', alpha=0.5, label='Aged VG')
plt.ylim(0.,10.)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.grid(True)
plt.legend(loc=2, fontsize= 16)
plt.show()
答案 0 :(得分:2)
当您使用bins=num_bins
时,每次调用plt.hist
都会决定bin边缘应该独立的位置。每次调用都会尝试选择适合传递数据的bin边。随着数据的变化,bin边缘也会发生变化。
要使bin宽度保持不变,您需要为每次调用plt.hist
传递相同的显式bin边缘数组:
num_bins = 50
data = np.concatenate([A,B,C,D])
min_data, max_data = data.min(), data.max()
bins = np.linspace(min_data, max_data, num_bins)
plt.hist(A, bins=bins, facecolor='blue', alpha=0.5, label='Healthy SG')
plt.hist(B, bins=bins, facecolor='red', alpha=0.5, label='Aged SG')
plt.hist(C, bins=bins, facecolor='yellow', alpha=0.5, label='Healthy VG')
plt.hist(D, bins=bins, facecolor='green', alpha=0.5, label='Aged VG')