为何模拟的Negative Binomial数据拟合分布与直方图匹配效果差?
问题根源与修正方案
你的代码有两个核心问题导致拟合效果差:
1. 直方图的bin设置与y轴尺度不匹配
负二项分布是离散分布,生成的数据都是整数,但你用bins=18会让每个bin包含多个整数,且y=..density..的计算逻辑是「频率/bin宽度」,而dnbinom返回的是每个整数点的概率质量(即该点出现的频率),两者尺度完全不对齐。
2. 离散分布用连续曲线绘制的偏差
stat_function默认绘制连续曲线,但负二项分布的概率只在整数点有意义,连续曲线会误导视觉对比。
修正后的代码
library(ggplot2) library(MASS) # 生成数据部分不变 n <- 1000 size <- 5 prob <- 0.3 negative_binomial <- rnbinom(n, size, prob) xx <- data.frame(negative_binomial) # 拟合参数 fit <- fitdistr(negative_binomial, densfun = "negative binomial") # 绘图调整 ggplot(data = xx, aes(x = negative_binomial)) + # 直方图:bin宽度设为1,对齐整数,y轴用频率(即概率) geom_histogram( aes(y = ..count../sum(..count..)), # 直接用频率(等于概率) binwidth = 1, boundary = 0.5, # 让bin边界在0.5、1.5...,每个bin对应一个整数 color = "black", fill = "lightblue" ) + # 用离散点+线段展示负二项分布的概率质量 stat_function( fun = dnbinom, args = list(mu = fit$estimate[2], size = fit$estimate[1]), color = "red", size = 1, geom = "point" # 用点展示每个整数点的概率 ) + stat_function( fun = dnbinom, args = list(mu = fit$estimate[2], size = fit$estimate[1]), color = "red", size = 0.8, geom = "line", linetype = "dashed", xlim = range(negative_binomial) # 限制线的范围在数据取值内 ) + labs(y = "概率")
关键调整说明
- 把
bins=18换成binwidth=1+boundary=0.5,确保每个bin对应一个整数,避免跨整数的分组。 - y轴用
..count../sum(..count..)直接计算频率(即每个取值的概率),和dnbinom返回的概率质量完全匹配。 - 用
geom="point"展示离散点的概率,搭配虚线连接,更贴合负二项分布的离散特性。
运行修正后的代码,你会发现直方图和拟合的负二项分布几乎完全重合。
内容的提问来源于stack exchange,提问作者Joe the Second
相关产品推荐
相关产品推荐

