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

如何在R的facet_wrap子图中移除指定分组的中位数线?

ggplot中facet_wrap指定子图移除中位数线的解决方案

你需要在分面绘图中移除Set 2子图的中位数线,保留其他子图的中位数线及所有子图的ID虚线连线,这里提供两种可行的解决方法:

原始代码

library(tidyverse)

score <- c(6,5,3,2,2,1,4,5,3,4,5,4,3,2,2,2,4,6)
time <- c(1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2)
set <- c(1,1,1,1,1,1,1,1,2,2,3,3,3,3,3,3,3,3)
ID <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9)

df <- data.frame(score, time, set, ID)

plot <- ggplot(df, aes(x = time, y = score, group = ID)) +
  geom_point(size = .5) +
  geom_line(linetype = 'dashed') +
  stat_summary(aes(group = 1, linetype = "median"), geom="line", fun = "median", size = .5) + 
  labs(linetype = "") +
  facet_wrap("set", ncol = 1) 
plot

解决方案一:过滤stat_summary的数据源

直接给stat_summary指定过滤后的数据,仅包含Set 1和Set 3的行,这样Set 2子图就不会生成中位数线:

library(tidyverse)

score <- c(6,5,3,2,2,1,4,5,3,4,5,4,3,2,2,2,4,6)
time <- c(1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2)
set <- c(1,1,1,1,1,1,1,1,2,2,3,3,3,3,3,3,3,3)
ID <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9)

df <- data.frame(score, time, set, ID)

plot <- ggplot(df, aes(x = time, y = score, group = ID)) +
  geom_point(size = .5) +
  geom_line(linetype = 'dashed') +
  # 过滤掉set==2的行,仅在Set1和Set3中绘制中位数线
  stat_summary(data = df %>% filter(set != 2), 
               aes(group = 1, linetype = "median"), 
               geom="line", fun = "median", size = .5) + 
  labs(linetype = "") +
  facet_wrap("set", ncol = 1) 
plot

解决方案二:通过映射动态隐藏中位数线

如果需要更灵活的控制,可以在aes中用ifelse判断set值,将Set 2的中位数线设置为完全透明:

plot <- ggplot(df, aes(x = time, y = score, group = ID)) +
  geom_point(size = .5) +
  geom_line(linetype = 'dashed') +
  stat_summary(aes(group = 1, linetype = "median", 
                   alpha = ifelse(set == 2, 0, 1)), 
               geom="line", fun = "median", size = .5) + 
  labs(linetype = "") +
  # 隐藏alpha对应的图例
  guides(alpha = "none") +
  facet_wrap("set", ncol = 1) 
plot

两种方法中,第一种逻辑更直接高效,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:32:50