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)

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

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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With