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

北城余情 提交于 2021-02-10 14:17:18

问题


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?

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

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()

回答1:


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()



来源:https://stackoverflow.com/questions/65606337/how-to-make-histograms-in-python-scipy-stats-look-as-good-as-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!