我用fitdist
包中的fitdistrplus
函数拟合了正态分布。使用denscomp
,qqcomp
,cdfcomp
和ppcomp
我们可以分别绘制histogram against fitted density functions
,theoretical quantiles against empirical ones
,the empirical cumulative distribution against fitted distribution functions
和theoretical probabilities against empirical ones
,如下所示。
set.seed(12345)
df <- rnorm(n=10, mean = 0, sd =1)
library(fitdistrplus)
fm1 <-fitdist(data = df, distr = "norm")
summary(fm1)
denscomp(ft = fm1, legendtext = "Normal")
qqcomp(ft = fm1, legendtext = "Normal")
cdfcomp(ft = fm1, legendtext = "Normal")
ppcomp(ft = fm1, legendtext = "Normal")
我非常有兴趣用
fitdist
绘制这些ggplot2
图。 MWE如下:qplot(df, geom = 'blank') +
geom_line(aes(y = ..density.., colour = 'Empirical'), stat = 'density') +
geom_histogram(aes(y = ..density..), fill = 'gray90', colour = 'gray40') +
geom_line(stat = 'function', fun = dnorm,
args = as.list(fm1$estimate), aes(colour = 'Normal')) +
scale_colour_manual(name = 'Density', values = c('red', 'blue'))
ggplot(data=df, aes(sample = df)) + stat_qq(dist = "norm", dparam = fm1$estimate)
如何开始用
fitdist
绘制这些ggplot2
图? 最佳答案
您可以使用类似这样的方法:
library(ggplot2)
ggplot(dataset, aes(x=variable)) +
geom_histogram(aes(y=..density..),binwidth=.5, colour="black", fill="white") +
stat_function(fun=dnorm, args=list(mean=mean(z), sd=sd(z)), aes(colour =
"gaussian", linetype = "gaussian")) +
stat_function(fun=dfun, aes(colour = "laplace", linetype = "laplace")) +
scale_colour_manual('',values=c("gaussian"="red", "laplace"="blue"))+
scale_linetype_manual('',values=c("gaussian"=1,"laplace"=1))
您只需要在运行图形之前定义
dfun
。在此示例中,它是Laplace发行版,但是您可以选择任何想要的版本,并根据需要添加更多的stat_function
。