I am trying to create a histogram plot with matplotlib. I am using bmi column from four different data frames (d1, d2, d2, d4).

The issue is that these 4 datasets have different sample sizes. So there is a disparity between the heights of the bar.

Is there any additional option in the matplotlib to normalize the heights of the bar?

import matplotlib.pyplot as plt

def bmiplot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/110.0, graphHeight/150.0), dpi=100)
    axes = f.add_subplot(111)

    d1 = dm_group1
    d2 = dm_group2
    d3 = dm_group3
    d4 = dm_group4

    plt.hist([d1.bmi.values.flatten(), d2.bmi.values.flatten(), d3.bmi.values.flatten(), d4.bmi.values.flatten()], 
    label=['bmi_dm1', 'bmi_dm2', 'bmi_dm3', 'bmi_dm4'])

graphWidth = 700
graphHeight = 800
bmiplot(graphWidth, graphHeight)


1 Answer 1


One approach is density, traditionally the code would be ...

kwargs = dict(histtype='stepfilled', alpha=0.4, normed=True, bins=50)

plt.hist(d1, **kwargs)
plt.hist(d2, **kwargs)
plt.hist(d3, **kwargs);

alpha is transparency allowing overlapping distributions.

Note normed is deprecated, the blurb here describes density now replacing it.

The blurb is here:

matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, ... **kwargs)

The definition of density is here

densitybool, default: False If True, draw and return a probability density: each bin will display the bin's raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1). If stacked is also True, the sum of the histograms is normalized to 1.

A different approach is relative frequency, via the weights command.

 plt.hist(mydata, weights= *)

*, relative counts per data type / total counts over all data types


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.