如何将负二项函数拟合到被GGR图中的因子包裹的数据?
我试图用负二项分布来拟合计数数据,但缩小到计数,就像在我的数据中一样,我必须分离出两个物种的二项函数。但是,要在函数中指定这一点,并在两个物种的键中获取带有参数值的线条图例,并不容易如何将负二项函数拟合到被GGR图中的因子包裹的数据?,r,ggplot2,distribution,data-fitting,R,Ggplot2,Distribution,Data Fitting,我试图用负二项分布来拟合计数数据,但缩小到计数,就像在我的数据中一样,我必须分离出两个物种的二项函数。但是,要在函数中指定这一点,并在两个物种的键中获取带有参数值的线条图例,并不容易 set.seed(111) count <- rbinom(500,100,0.1) species <- rep(c("A","B"),time = 250) df <- data.frame(count,species) #Specifying negative binomial func
set.seed(111)
count <- rbinom(500,100,0.1)
species <- rep(c("A","B"),time = 250)
df <- data.frame(count,species)
#Specifying negative binomial function
negbinom.params <- fitdistr(df$count,"negative binomial", method = "SANN")$estimate
dist.params <- map(list(`Negative Binomial` = negbinom.params),~ map2(names(.),.,~ paste0(.x," = ",round(.y,2))) %>% unlist %>% paste0(.,collapse = ", ")) %>% map2_chr(names(.),., ~ paste(.x,.y,sep=":\n"))
#Plotting
mybinwidth = 2
ggplot(df, aes(x = count, colour = species, fill = species)) +
facet_grid(.~species) +
geom_histogram(aes(y=..count..),alpha = 0.5, binwidth = mybinwidth) +
stat_function(aes(color = "orange"),
fun = function(x,size, mu) {
mybinwidth * nrow(df) * dnbinom(x,size = size, mu = mu)
},
args=fitdistr(df$count, "negative binomial", method="SANN")$estimate,
xlim=c(0,50),n=20)
set.seed(111)
计数你是对的,这是一个有点痛苦的权利。我对您的示例进行了一些修改,以便更清楚地显示两种不同的分布。以下是我试图使您的方法发挥作用的尝试:
库(ggplot2)
图书馆(弥撒)
#>警告:包“质量”是在R版本3.6.2下生成的
种子(111)
是我做了一些愚蠢的事情还是它也给了你+37个警告?我也得到了37个警告..这太神奇了!我仍然觉得实现第二种替代方法有点困难。RN,看起来“ggh4x”不是R中的软件包。所以我使用了您在上的安装代码。但它不会从github和syas加载“错误:无法从github安装'ggh4x'(从警告转换而来)安装软件包”你说得对,它不在CRAN上,我认为它没有足够的主体来安装CRAN。我在本地机器上也遇到了这个错误,对我来说,它通过重新安装Rcpp包得到了修复。
library(ggh4x)
ggplot(df, aes(count)) +
geom_histogram(binwidth = mybinwidth,
aes(fill = species), alpha = 0.5,
position = "identity") +
stat_theodensity(aes(colour = species,
y = after_stat(count * mybinwidth)),
distri = "nbinom") +
scale_colour_discrete(labels = unname(ests), name = "fit") +
facet_wrap(~ species)