简体   繁体   English

Python-Matplotlib多直方图

[英]Python - Matplotlib Multi histograms

I would like to plot several histograms but sometimes bins are larger than others. 我想绘制几个直方图,但有时bin大于其他的。 I cant explain why i obtain that...you can see a plot below, red bins have a great width than others. 我无法解释为什么我得到...您可以在下面看到一个图,红色垃圾箱的宽度比其他垃圾箱大。 My code is shown below the figure 我的代码如下图所示

在此处输入图片说明

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()

When you use bins=num_bins , each call to plt.hist decides where the bin edges should be independently . 使用bins=num_bins ,对plt.hist每次调用plt.hist确定bin边缘应独立 plt.hist何处。 Each call tries to choose bin edges which are appropriate for the data passed. 每个调用都尝试选择适合于所传递数据的bin边缘。 As the data changes, so do the bin edges. 随着数据的变化,垃圾箱边缘也会变化。

To make the bin widths constant, you'll need to pass the same explicit array of bin edges to each call to plt.hist : 为了使bin宽度恒定,您需要将相同的显式bin边缘数组传递给对plt.hist每次调用:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM