I'm trying to fit a negative binomial distribution to counts data but scaled back to counts like in this example In my data, I have to separate out the binomial function plotting for two species. However, there is not easy way to specify this within the function and getting the line legends with parameter values in the key for both species.
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)