user3601754 user3601754 - 1 year ago 104
Python Question

Python - Matplotlib Multi histograms

I would like to plot several histograms but sometimes bins are larger than others. I cant explain why i obtain 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'}

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.tick_params(axis='both', which='major', labelsize=14)
plt.legend(loc=2, fontsize= 16)

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download