Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a histogram using Python just like using R hist function

I'm trying to do a histogram in Python just like I did in R. How can I do it?

R:

age <- c(43, 23, 56, 34, 38, 37, 41)
hist(age)

R output

Python:

age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age)

matplotlib output

like image 299
letsplay Avatar asked Feb 12 '26 21:02

letsplay


1 Answers

The difference here is caused by the way R and matplotlib choose the number of bins by default.

For this particular example you can use:

age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age, bins=4)

to replicate the R-style histogram.

General Case

If we want to have matplotlib's histograms look like R's in general, all we need to do is replicate the binning logic that R uses. Internally, R uses Sturges' Formula* to calculate the number of bins. matplotlib supports this out of the box, we just have to pass 'sturges' for the bins argument.

age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age, bins='sturges')

* It's a little bit more complicated internally, but this gets us most of the way there.

like image 97
Ammar Askar Avatar answered Feb 14 '26 12:02

Ammar Askar