r - 如何在相同的 ggplot2 (R) 上拟合负二项式、正态和泊松密度函数但缩放到计数数据?
问题描述
我有一些计数数据。我想用计数数据绘制直方图并添加负二项式、正态和泊松密度函数,但将函数拟合到计数数据。
我尝试按照这个示例进行操作,但是(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)
推荐阅读
- javascript - forEach 遍历对象并使用 document.write() 打印;
- android - 如何在每个项目中使用 EditText 实现 Recyclerview 并使用 SearchView 过滤列表?
- go - 如何在 Proto3 中为 HTTP 响应创建可空字段?
- angular - 我如何告诉 Angular 安装 Clarity 模块的一个子集?
- java - 在带有 JFrame 表单的 Netbeans derby 中使用带有 WHERE 子句的 SELECT 语句
- python-3.x - TypeError: __init__() 接受 4 个位置参数,但给出了 5 个,添加所有元素在访问元素时仍然存在问题
- python - 如何在 Python 中 Sagemaker 的 XGBoost 训练作业中指定 content_type?
- javascript - 剑道图表系列单击事件左键单击未触发但右键单击是
- c# - 您可以使用反射更改 DateTime 对象中 _dateData 的私有字段值吗?
- python - 检查谜语答案的 Python 程序