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

如何将stat_poly_eq()的输出信息移至ggplot图表副标题?

解决方案

要把stat_poly_eq()的输出移到图表副标题,核心思路是先手动拟合分组模型、提取所需统计量,再将格式化后的文本传入ggtitle()的subtitle参数。具体步骤如下:

1. 提取分组统计信息

先对每个Type分组拟合线性模型,提取回归方程、R²和p值,并格式化为和stat_poly_eq()一致的文本:

library(ggplot2)
library(ggpmisc)
library(dplyr)
library(broom)

# 加载数据
t1c11<-structure(list(Year = c(2000, 2001, 2002, 2003, 2004, 2000, 2001, 
2002, 2003), TreeCover = c(48.852632, 50.463158, 51.294737, 52.663158, 
52.747368, 57, 54.6, 42.066667, 51), TC_Avg3 = c(NA, 50.203509, 
51.4736843333333, 52.2350876666667, 52.045614, NA, 51.2222223333333, 
49.2222223333333, 47.8), Type = structure(c(30L, 30L, 30L, 30L, 
30L, 1L, 1L, 1L, 1L), levels = c("C 1-1", "C 1-2", "C 1-3", "C 1-4", 
"C 1-5", "C 1-6", "C 2-1", "C 2-2", "C 2-3", "C 2-4", "C 3-1", 
"C 3-2", "C 3-3", "C 3-4", "C 4-1", "C 4-2", "C 4-3", "C 4-4", 
"C 5-1", "C 5-2", "C 5-3", "C 6-1", "C 6-2", "C 6-3", "C 6-4", 
"C 7-1", "C 7-2", "C 7-3", "C 7-4", "T 1", "T 2"), class = "factor")), row.names = c(1L, 
2L, 3L, 4L, 5L, 47L, 48L, 49L, 50L), class = "data.frame")

# 分组拟合模型并提取统计量
stats_text <- t1c11 %>%
  filter(!is.na(TC_Avg3)) %>%
  group_by(Type) %>%
  do(model = lm(TC_Avg3 ~ Year, data = .)) %>%
  mutate(
    # 提取回归方程系数,保留2位小数
    eq = paste0("y = ", round(coef(model)[[1]], 2), " + ", round(coef(model)[[2]], 2), "x"),
    # 提取R²,保留3位小数
    r2 = paste0("R² = ", round(summary(model)$r.squared, 3)),
    # 提取p值,保留3位小数
    p_val = paste0("p = ", round(summary(model)$coefficients[2,4], 3))
  ) %>%
  # 组合每组的信息,用换行分隔
  summarise(text = paste0(Type, ": ", eq, ", ", r2, ", ", p_val, collapse = "\n")) %>%
  pull(text)

2. 绘制图表并设置副标题

将提取到的统计文本作为副标题传入ggtitle(),同时去掉原有的stat_poly_eq():

ggplot(t1c11, aes(x=Year, y=TC_Avg3, colour = Type)) +
  geom_point() +
  geom_smooth(method = "lm", span=2) + # 指定线性模型,与stat_poly_eq默认逻辑一致
  scale_colour_manual(values=c('#7a7a7a','#2c9399'))+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+
  ggtitle(label = "Test", subtitle = stats_text)

补充说明

  • 如果需要和stat_poly_eq()完全一致的格式(比如用希腊字母表示R²),可以用ggpmisc包中的format.beta()等函数优化文本格式;
  • 该方法可封装成函数批量处理,适配你生成60张图表的需求,只需循环传入不同数据集即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:35:24