Search code examples
pythonmatplotlibseabornhistogram

How to make histograms in Python (scipy.stats) look as good as R?


The following plot and its code were generated in R (source). How can I replicate this quality of a histogram in Python code using scipy.stats?

enter image description here

x = rgamma(1000, 3, .1)
hist(x, prob=T, br=30, col="skyblue2", main="n = 1000: GAMMA(3, .1)")
curve(dgamma(x, 3, .1), add=T, lwd=2, col="orange")
abline(v = 55.81, lwd=2, col="blue")
abline(v = 53.2232, lwd=2, col="brown", lty="dotted")

The R plot above is alot better than Python's scipy.stats histograms, one example shown below, but I know there are alternative plot libraries for python

enter image description here

from scipy.stats import dgamma
r = dgamma.rvs(1.1, size=1000)
ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)
ax.legend(loc='best', frameon=False)
plt.show()

Solution

  • You could use a seaborn histplot + kdeplot if you want the kde to be a different color. Regarding your comment and having the kde as a different color, I commented on this github here where someone had a similar question (I believe this is best way to do this in 2021). So, we are able to get very close to what you have posted with R with a little bit more code. There are many other parameters that you can pass directly to sns.histplot and sns.kdeplot or if the parameter doesn't exist you can add stuff with plt e.g. plt.title('Seaborn Histplot Example') or add stuff to axes with ax..

    from scipy.stats import dgamma
    import matplotlib.pyplot as plt
    import seaborn as sns
    r = dgamma.rvs(1.1, size=1000)
    sns.set_style("white")
    sns.set_context("talk")
    fig, ax = plt.subplots(figsize=(24,12))
    sns.histplot(r, color='deepskyblue', stat='density')
    sns.kdeplot(r, color='orange')
    plt.title('Seaborn Histplot Example', size=24, fontweight='bold')
    sns.histplot(r, color='deepskyblue', stat='density', edgecolor="black")
    sns.kdeplot(r, color='orange')
    plt.axvline(2.8, 0, 0.95, color='blue')
    plt.axvline(2.4, 0, 0.95, color='brown', linestyle='--')
    ax.tick_params(left=True, bottom=True)
    plt.show()
    

    enter image description here