Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...