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

如何在ggplot2的geom_smooth与facet_grid中按模型显著性区分线型

解决方法

要实现分面后根据线性模型显著性设置回归线样式,核心是先提前计算每个分面组的模型p值,再将p值关联到原数据,最后在geom_smooth里根据p值映射样式。具体步骤如下:

1. 提前计算分组的模型显著性(p值)

用dplyr分组计算,搭配broom包提取线性模型的p值(未安装broom的话先运行install.packages("broom")):

library(dplyr)
library(broom)

# 按Orig_Biot分组,计算每个组线性模型的自变量p值
model_stats <- Umw_Daten %>%
  group_by(Orig_Biot) %>%
  summarize(
    p_value = tidy(lm(Richness ~ Jahr_int, data = cur_data())) %>%
      filter(term == "Jahr_int") %>%
      pull(p.value)
  )

# 将p值合并回原数据框,让每个观测对应所在分组的显著性结果
Umw_Daten <- Umw_Daten %>%
  left_join(model_stats, by = "Orig_Biot")

2. 修改ggplot代码,根据p值设置回归线样式

在geom_smooth里通过aes映射color和linetype到p值的判断结果,再用scale_*_manual指定对应样式:

library(ggplot2)
library(ggpubr) # 用到stat_cor需要加载这个包

rich <- ggplot(Umw_Daten, aes(x=Jahr_int, y=Richness)) + 
  geom_point(size=2) +
  facet_grid(Orig_Biot~., scales = "free", space="free") +
  # 根据p值判断显著性,映射颜色和线型
  geom_smooth(
    formula= y~x, 
    method = lm,
    aes(
      color = ifelse(p_value < 0.05, "显著", "不显著"),
      linetype = ifelse(p_value < 0.05, "显著", "不显著")
    )
  ) +
  # 手动指定对应样式:显著为绿色实线,不显著为红色虚线
  scale_color_manual(values = c("显著" = "green4", "不显著" = "indianred2")) +
  scale_linetype_manual(values = c("显著" = "solid", "不显著" = "11")) +
  theme_light()+
  stat_cor(aes(label = paste(..rr.label..)), r.accuracy = 0.01)+
  stat_cor(aes(label = paste( ..p.label..)),method = "pearson", p.accuracy = 0.001)

print(rich)

补充说明

  • 代码默认用p<0.05作为显著性阈值,需要调整的话,把ifelse里的0.05改成你需要的数值即可。
  • 不需要图例的话,在geom_smooth里添加show.legend = FALSE,或者用theme(legend.position = "none")隐藏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:35:30