You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何绘制混合Gamma分布?已生成样本求后续绘图方法

混合Gamma分布绘图方案

不需要单独生成五个变量的向量,你已经通过sample和rgamma生成了完全符合要求的混合分布样本x,直接基于这个样本就能完成绘图。以下是几种常见的绘图实现方式:

1. 基础R绘图(快速直观)

用直方图搭配核密度估计,展示混合分布的整体形态:

# 绘制直方图,freq=FALSE转为密度刻度,方便和核密度曲线对齐
hist(x, breaks = 30, freq = FALSE, col = "lightblue", 
     main = "5个Gamma分布的混合分布", xlab = "取值")
# 添加样本的核密度曲线
lines(density(x), col = "red", lwd = 2)

2. ggplot2绘图(美观易定制)

如果习惯用tidyverse生态的ggplot2,代码如下:

library(ggplot2)

# 将样本转为数据框,适配ggplot2的输入格式
sample_df <- data.frame(value = x)

ggplot(sample_df, aes(x = value)) +
  geom_histogram(aes(y = after_stat(density)), bins = 30, 
                 fill = "lightblue", alpha = 0.7, color = "white") +
  geom_density(color = "darkred", linewidth = 1.2) +
  labs(title = "5个Gamma混合分布的样本分布", x = "x", y = "密度") +
  theme_minimal()

3. 可选:叠加理论混合密度与单个成分(用于对比)

如果想验证样本是否符合理论分布,或者查看单个Gamma成分的贡献,可以计算理论密度并叠加:

# 生成连续的x轴序列
x_range <- seq(min(x), max(x), length.out = 1000)

# 计算每个Gamma成分的密度(乘以对应权重θ_i)
comp1 <- dgamma(x_range, shape = 3, rate = 1/1) * (1/15)
comp2 <- dgamma(x_range, shape = 3, rate = 1/2) * (2/15)
comp3 <- dgamma(x_range, shape = 3, rate = 1/3) * (3/15)
comp4 <- dgamma(x_range, shape = 3, rate = 1/4) * (4/15)
comp5 <- dgamma(x_range, shape = 3, rate = 1/5) * (5/15)

# 计算理论混合密度
theoretical_mix <- comp1 + comp2 + comp3 + comp4 + comp5

# 绘图对比
hist(x, breaks = 30, freq = FALSE, col = "lightblue", 
     main = "混合Gamma分布:样本vs理论", xlab = "x")
lines(density(x), col = "red", lwd = 2, lty = 1)  # 样本核密度
lines(x_range, theoretical_mix, col = "darkgreen", lwd = 2, lty = 2)  # 理论混合密度

# 可选:叠加单个成分的密度(放大15倍以便观察形态)
lines(x_range, comp1*15, col = "orange", lwd = 1, lty = 3)
lines(x_range, comp2*15, col = "purple", lwd = 1, lty = 3)
lines(x_range, comp3*15, col = "brown", lwd = 1, lty = 3)
lines(x_range, comp4*15, col = "pink", lwd = 1, lty = 3)
lines(x_range, comp5*15, col = "gray", lwd = 1, lty = 3)

# 添加图例
legend("topright", 
       legend = c("样本核密度", "理论混合密度", "单个Gamma成分(放大15倍)"),
       col = c("red", "darkgreen", "orange"),
       lty = c(1, 2, 3),
       lwd = 2)

内容的提问来源于stack exchange,提问作者Laura Jarosz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:10:18