我有一些计数数据。我想用计数数据绘制直方图,并添加负二项式,正态和泊松密度函数,但将这些函数拟合到计数数据中。
我尝试按照以下示例进行操作,但(a)我无法拟合负二项式和泊松函数(b)在将其缩放到计数数据级别时无法接近的地方(c)不知道如何在同一个图上将所有三个图例都带有图例(d)行另外,我如何获得每个拟合的基本统计信息?例如,负二项式拟合将生成参数k。我如何使它出现在情节上
set.seed(111)
counts <- rbinom(500,100,0.1)
df <- data.frame(counts)
ggplot(df, aes(x = counts)) +
geom_histogram(aes(y=..density..),colour = "black", fill = "white") +
stat_function(fun=dnorm,args=fitdistr(df$counts,"normal")$estimate)
ggplot(df, aes(x = counts)) +
geom_histogram(aes(y=..density..),colour = "black", fill = "white") +
stat_function(fun=poisson,args=fitdistr(df$counts,"poisson")$estimate)
ggplot(df, aes(x = counts)) +
geom_histogram(aes(y=..density..),colour = "black", fill = "white") +
stat_function(fun=dnbinom,args=fitdistr(df$counts,"dnbinom")$estimate)
您有几个问题,首先"dnbinom"
是的无效分配MASS::fitdistr
。其次,MASS::fitdistr
由于无法使用默认方法,因此我们可以使用method = "SANN"
。第三,除非另有说明,否则stat_function
尝试以dnbinom
非整数值进行评估,这是行不通的。
使参数显示在图例中有些棘手,因为您必须在ggplot
调用之外估计它们。我很懒惰并且习惯了purrr::map2
,但是您可以使用一些基本的R函数来做同样的事情。
library(purrr)
library(dplyr)
norm.params <- fitdistr(df$counts,"normal")$estimate
poisson.params <- fitdistr(df$counts,"poisson")$estimate
negbinom.params <- fitdistr(df$counts,"negative binomial", method = "SANN")$estimate
dist.params <- map(list(Normal = norm.params,Poisson = poisson.params,`Negative Binomial` = negbinom.params),
~ map2(names(.),.,~ paste0(.x," = ",round(.y,2))) %>% unlist %>% paste0(.,collapse = ", ")) %>%
map2_chr(names(.),., ~ paste(.x,.y,sep=":\n"))
最后,如果要按计数扩展(如本答案所示),则只需定义匿名函数。
mybinwidth = 1
ggplot(df, aes(x = counts)) +
geom_histogram(aes(y=..count..),colour = "black", fill = "white", binwidth = mybinwidth) +
stat_function(aes(color = "black"),fun=function(x,mean,sd) mybinwidth * nrow(df) * dnorm(x,mean, sd),
args=fitdistr(df$counts,"normal")$estimate) +
stat_function(aes(color = "blue"),fun=function(x,lambda) mybinwidth * nrow(df) * dpois(x,lambda),
args=fitdistr(df$counts,"poisson")$estimate,
xlim=c(1,20), n=20) +
stat_function(aes(color = "orange"),fun=function(x,size, mu) mybinwidth * nrow(df) * dnbinom(x,size = size, mu = mu),
args=fitdistr(df$counts,"negative binomial", method="SANN")$estimate,
xlim=c(1,20),n=20) +
scale_color_manual("Distribution", values=c(black="black",blue="blue",orange="orange"),
labels=dist.params)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句