R语言t分布密度与分布函数多参数同图绘制作业问询
嘿,我来帮你理清这个统计学绘图的问题,先纠正下你当前的思路,再给你完整的实现方案~
一、先纠正你目前的思路偏差
你用rnorm(20, 0, 1)生成x的方式并不适合绘制理论密度/分布函数曲线——我们需要的是连续覆盖函数主要取值范围的x轴序列,而非随机样本;另外完全不需要生成4组x值,同一组连续x就能对应不同参数(比如不同自由度)的函数值。
二、t分布的完整绘图实现(密度+分布函数内嵌布局)
下面是针对4组自由度参数,把密度函数和分布函数(CDF)放在同一幅图里的R代码:
1. 准备基础数据
# 生成覆盖t分布核心取值范围的连续x序列,步长越小曲线越平滑 x <- seq(-5, 5, by = 0.01) # 定义4组对比的自由度参数 df_list <- c(1, 3, 7, 30) # 给每组参数分配不同颜色,方便区分 colors <- c("red", "blue", "green", "purple")
2. 绘制内嵌双图(密度+CDF)
用layout()实现上下布局的内嵌图,比par(new=TRUE)更直观:
# 设置布局:2行1列,上下放置密度图和CDF图 layout(matrix(c(1, 2), nrow = 2, ncol = 1)) ### 第一个图:t分布密度函数 plot(x, dt(x, df = df_list[1]), type = "l", col = colors[1], xlab = "x", ylab = "Density", main = "t-distribution: Density & CDF", lwd = 2) # 叠加其他自由度的密度曲线 for (i in 2:length(df_list)) { lines(x, dt(x, df = df_list[i]), col = colors[i], lwd = 2) } # 添加图例,明确各组参数 legend("topright", legend = paste("df =", df_list), col = colors, lwd = 2, cex = 0.8) ### 第二个图:t分布累积分布函数(CDF) plot(x, pt(x, df = df_list[1]), type = "l", col = colors[1], xlab = "x", ylab = "Cumulative Probability", lwd = 2) # 叠加其他自由度的CDF曲线 for (i in 2:length(df_list)) { lines(x, pt(x, df = df_list[i]), col = colors[i], lwd = 2) } legend("bottomright", legend = paste("df =", df_list), col = colors, lwd = 2, cex = 0.8) # 恢复默认绘图布局 layout(1)
三、扩展到卡方分布和F分布的通用思路
逻辑和t分布完全一致,只需要替换对应的分布函数和参数范围:
- 卡方分布:用
dchisq()(密度)、pchisq()(CDF),参数为自由度df,x取值范围改为seq(0, 15, by = 0.01)(因为卡方分布非负) - F分布:用
df()(密度)、pf()(CDF),参数为分子自由度df1和分母自由度df2,比如选4组参数:(1,1), (3,5), (10,10), (20,50),x范围改为seq(0, 5, by = 0.01)
举个卡方分布的代码片段示例:
x_chisq <- seq(0, 15, by = 0.01) df_chisq <- c(1, 4, 8, 15) colors <- c("red", "blue", "green", "purple") layout(matrix(c(1, 2), nrow = 2)) # 卡方密度图 plot(x_chisq, dchisq(x_chisq, df = df_chisq[1]), type = "l", col = colors[1], xlab = "x", ylab = "Density", main = "Chi-square Distribution: Density & CDF", lwd = 2) for (i in 2:length(df_chisq)) { lines(x_chisq, dchisq(x_chisq, df = df_chisq[i]), col = colors[i], lwd = 2) } legend("topright", legend = paste("df =", df_chisq), col = colors, lwd = 2, cex = 0.8) # 卡方CDF图 plot(x_chisq, pchisq(x_chisq, df = df_chisq[1]), type = "l", col = colors[1], xlab = "x", ylab = "Cumulative Probability", lwd = 2) for (i in 2:length(df_chisq)) { lines(x_chisq, pchisq(x_chisq, df = df_chisq[i]), col = colors[i], lwd = 2) } legend("bottomright", legend = paste("df =", df_chisq), col = colors, lwd = 2, cex = 0.8) layout(1)
四、关键注意事项总结
- 不要用随机样本生成x轴,要用
seq()生成连续序列,才能得到平滑的理论曲线 - 同一组x可复用在所有参数的函数计算中,无需重复生成
- 用
plot()初始化第一个曲线,再用lines()叠加其他曲线,实现多曲线同图 - 用
layout()或par(mfrow=c(2,1))轻松实现内嵌/上下布局的双图 - 一定要加图例,明确区分不同参数对应的曲线
内容的提问来源于stack exchange,提问作者Adi Pîslaru




