我用fitdist包中的fitdistrplus函数拟合了正态分布。使用denscompqqcompcdfcompppcomp我们可以分别绘制histogram against fitted density functionstheoretical quantiles against empirical onesthe empirical cumulative distribution against fitted distribution functionstheoretical 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")


r - 用ggplot2制作fitdist图-LMLPHP

qqcomp(ft = fm1, legendtext = "Normal")


r - 用ggplot2制作fitdist图-LMLPHP

cdfcomp(ft = fm1, legendtext = "Normal")


r - 用ggplot2制作fitdist图-LMLPHP

ppcomp(ft = fm1, legendtext = "Normal")


r - 用ggplot2制作fitdist图-LMLPHP

我非常有兴趣用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'))


r - 用ggplot2制作fitdist图-LMLPHP

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

08-07 12:13