如何使Python中的直方图(scipy.stats)看起来和R一样好? [英] How to make histograms in Python (scipy.stats) look as good as R?
问题描述
以下图及其代码是在R(
x = rgamma(1000,3,.1)hist(x,prob = T,br = 30,col ="skyblue2",main ="n = 1000:GAMMA(3,.1)"))曲线(dgamma(x,3,.1),add = T,lwd = 2,col =橙色")绝对(v = 55.81,lwd = 2,col =蓝色")绝对值(v = 53.2232,lwd = 2,col =棕色",lty =虚线")
上面的R图比Python的
从scipy.stats中的 导入dgammar = dgamma.rvs(1.1,size = 1000)ax.hist(r,density = True,histtype ='stepfilled',alpha = 0.2)ax.legend(loc ='best',frameon = False)plt.show()
如果需要,可以使用 seaborn
histplot
+ kdeplot
kde
是另一种颜色.关于您的评论以及kde为其他颜色,我在此github上发表了评论,其中
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()
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()
这篇关于如何使Python中的直方图(scipy.stats)看起来和R一样好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!