user3601754
user3601754

Reputation: 3862

Python - Matplotlib Multi histograms

I would like to plot several histograms but sometimes bins are larger than others. 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

enter image description here

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

Upvotes: 0

Views: 139

Answers (1)

unutbu
unutbu

Reputation: 879591

When you use bins=num_bins, each call to plt.hist decides where the bin edges should be independently. Each call tries to choose bin edges which are appropriate for the data passed. 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:

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

Upvotes: 2

Related Questions