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

3lxsmp7m  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(81)

我正在处理一个数据集,我认为它遵循“Negative Binomial”分布。然而,当我拟合 Negative Binomial 分布时,结果发现它拟合得不好。为了进一步探索,我模拟了一个Negative Binomial分布,但即使在模拟数据上,叠加分布也没有提供良好的拟合。
以下是我的模拟数据:

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)

字符串
我想创建一个直方图,在这个数据上覆盖“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,为什么叠加分布提供的数据拟合如此之差?我做错了什么?


的数据

0h4hbjxa

0h4hbjxa1#

主要的问题是,你试图绘制一个离散分布,但给密度函数输入连续值(这意味着它对大多数连续值返回0)。

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

yy <- data.frame(negative_binomial = 0:45)
yy$density <- dnbinom(yy$negative_binomial, 
                     mu = fit$estimate["mu"] , size = fit$estimate["size"])

ggplot(data = xx, aes(negative_binomial)) +
  geom_histogram(
    aes(y = ..density..),
    binwidth = 1, color = "black", fill = "lightblue") +
  geom_linerange(data = yy, aes(ymin = 0, ymax = density),
                color = "red")

字符串


的数据

相关问题