How to plot a histogram using Matplotlib in Python with a list of data?

If you want a histogram, you don’t need to attach any ‘names’ to x-values because:

  • on x-axis you will have data bins
  • on y-axis counts (by default) or frequencies (density=True)
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

x = np.random.normal(size=1000)

plt.hist(x, density=True, bins=30)  # density=False would make counts

enter image description here

Note, the number of bins=30 was chosen arbitrarily, and there is Freedman–Diaconis rule to be more scientific in choosing the “right” bin width:

![enter image description here , where IQR is Interquartile range and n is total number of datapoints to plot

So, according to this rule one may calculate number of bins as:

q25, q75 = np.percentile(x, [25, 75])
bin_width = 2 * (q75 - q25) * len(x) ** (-1/3)
bins = round((x.max() - x.min()) / bin_width)
print("Freedman–Diaconis number of bins:", bins)
plt.hist(x, bins=bins);

Freedman–Diaconis number of bins: 82

enter image description here

And finally you can make your histogram a bit fancier with PDF line, titles, and legend:

import scipy.stats as st

plt.hist(x, density=True, bins=82, label="Data")
mn, mx = plt.xlim()
plt.xlim(mn, mx)
kde_xs = np.linspace(mn, mx, 300)
kde = st.gaussian_kde(x)
plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
plt.legend(loc="upper left")

enter image description here

If you’re willing to explore other opportunities, there is a shortcut with seaborn:

# !pip install seaborn
import seaborn as sns
sns.displot(x, bins=82, kde=True);

enter image description here

Now back to the OP.

If you have limited number of data points, a bar plot would make more sense to represent your data. Then you may attach labels to x-axis:

x = np.arange(3), height=[1,2,3])
plt.xticks(x, ['a','b','c']);

enter image description here

Leave a Comment