Why are the columns in the matplotlib histogram not on top of the numbers

Viewed 457

I would expect every column to be centered on top of their bin number. Instead, the 1 and 2 bars are right of the number, the 3rd on to the left. Why is it not even consistent?

histogram plot

import matplotlib.pyplot as plt

degrees = [1, 1, 2, 2, 2, 2, 3]
plt.hist(degrees)
plt.show()
2 Answers

Short answer: It is not supposed to, use plt.bar() instead. For longer explanation, please read below.

Why bars are not on top of numbers 1,2&3?

The purpose of a histogram is to approximate the distribution of the data. For example

import numpy as np
plt.hist(np.random.normal(3, 7, 100))

which gives

enter image description here

Now, when you have much less data, which is integer valued, and call

plt.hist([1, 1, 2, 2, 2, 2, 3])

you also get approximation of the distribution of the data you provided. With the default parameters it looks like this:

enter image description here

The documentation of hist tells that

  • If you do not provide bins, it will default to 10.
  • If you do not provide range, it will default to min and max of your data

Therefore, your data will be put inside 10 bins, with min at 1 and max at 3. These bins will be

In [45]: np.linspace(1,3, 11)
Out[45]: array([1. , 1.2, 1.4, 1.6, 1.8, 2. , 2.2, 2.4, 2.6, 2.8, 3. ])

Since you have only data inside bins 1.0 - 1.2, 2.0 - 2.2 and 2.8 - 3.0, you will see three bars centered at 1.1, 2.1 and 2.9.

A guess of what you're after

If your data is integer (categorical) valued, like

degrees = [1, 1, 2, 2, 2, 2, 3]

and you want to know the relative sizes of these categories, you probably want to create a bar plot instead.

enter image description here

import matplotlib.pyplot as plt
from collections import Counter

degrees = [1, 1, 2, 2, 2, 2, 3]
counts = Counter(degrees)

plt.bar(counts.keys(), counts.values())
plt.show()

Because you didn't specify the bins. If you add the bins in:

degrees = [1, 1, 2, 2, 2, 2, 3]
plt.hist(degrees, bins=[1,2,3,4])
plt.show()

enter image description here

Related