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

如何用ggplot绘制F统计量与p值并在图下方嵌入相关信息

使用ggplot绘制并嵌入F统计量与p值

1. 先计算F统计量与p值

ggplot仅负责可视化,统计量需要先通过统计模型计算。以下是两种常见场景的计算方式:

场景1:单因素方差分析(分组差异检验)

# 加载依赖包
library(ggplot2)
library(broom)

# 用内置数据集mtcars演示
data(mtcars)

# 拟合方差分析模型
anova_model <- aov(mpg ~ cyl, data = mtcars)
# 提取结构化结果
anova_result <- tidy(anova_model)

# 提取并格式化统计量(保留2位/4位小数)
f_stat <- round(anova_result$statistic[1], 2)
p_val <- round(anova_result$p.value[1], 4)

场景2:线性回归的F统计量

# 拟合线性回归模型
lm_model <- lm(mpg ~ wt, data = mtcars)
# 提取F统计量
f_stat <- round(summary(lm_model)$fstatistic[1], 2)
# 计算对应的p值
p_val <- round(pf(summary(lm_model)$fstatistic[1], 
                  summary(lm_model)$fstatistic[2], 
                  summary(lm_model)$fstatistic[3], 
                  lower.tail = FALSE), 4)

2. 用ggplot绘制基础图形

以分组箱线图为例(展示不同气缸数的油耗差异):

base_plot <- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
  geom_boxplot(fill = "#4292c6", color = "black") +
  labs(title = "不同气缸数的汽车油耗对比",
       x = "气缸数",
       y = "每加仑英里数(mpg)") +
  theme_minimal()

3. 在图下方嵌入统计信息

方法1:用图标题栏的caption(绘图区域外,贴近示例效果)

统计信息显示在图的底部居中位置:

base_plot + 
  labs(caption = paste0("F统计量 = ", f_stat, ",p值 = ", p_val)) +
  theme(plot.caption = element_text(hjust = 0.5, size = 10, margin = margin(t = 10)))

方法2:在绘图区域内添加文本

如果需要把统计信息放在绘图区域底部(避免超出图边界):

base_plot + 
  annotate("text", 
           x = median(as.numeric(factor(mtcars$cyl))),  # 居中对齐x轴
           y = min(mtcars$mpg) - 1.5,  # 调整y轴位置避免遮挡数据
           label = paste0("F = ", f_stat, ",p = ", p_val),
           size = 4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:03:14