如何使用 ggplot2() 在直方图上拟合“负二项式”分布?

问题描述 投票:0回答:1

我正在使用一个数据集,我认为该数据集遵循“负二项式”分布。然而,当我拟合“负二项式”分布时,结果证明拟合效果很差。为了进一步探索,我模拟了负二项式分布,但即使在模拟数据上,叠加分布也无法提供良好的拟合。 这是我的模拟数据:

library(ggplot2) library(MASS) library(fitdistrplus) # Generating negative binomial random numbers n <- 1000 # Number of random numbers size <- 5 # Number of successes prob <- 0.3 # Probability of success # Generating negative binomial random numbers negative_binomial <- rnbinom(n, size, prob) xx <- data.frame(negative_binomial)

我想创建一个直方图,在此数据上叠加“
负二项式

”分布。假设我得到了这些数据,所以我必须使用 fitdist() 来估计分布的参数。

fit <- fitdistr(negative_binomial,densfun = "negative binomial")
ggplot(data = xx, aes(negative_binomial)) +
  geom_histogram(
    aes(y = ..density..),
    bins = 18, color = "black", fill = "lightblue") +
  stat_function(fun = dnbinom ,
    args = list(mu = fit$estimate[2] , size = fit$estimate[1]),
    color = "red", size = 1)

问题

:尽管知道模拟数据是Negative Binomial,但为什么叠加分布与数据的拟合度如此差?我做错了什么?

r ggplot2 histogram distribution
1个回答
0
投票

适合

yy<- fitdist(negative_binomial, distr = "nbinom")

ggplot(数据 = xx, aes(负二项式)) + 几何直方图( aes(y = ..密度..), 垃圾箱= 13,颜色=“黑色”,填充=“浅蓝色”)+ geom_col(数据 = yy, aes(y = 密度), 颜色=“红色”,填充=NA,大小=1)<- data.frame(negative_binomial = 0:45) yy$density <- dnbinom(yy$negative_binomial, mu = fit$estimate["mu"] , size = fit$estimate["size"])

© www.soinside.com 2019 - 2024. All rights reserved.