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

在ggplot中移除图例特定项且保留原有绘图美学效果

移除ggplot图例指定项并保留原有绘图样式

问题说明

需要移除绘图图例中带有“no pipe”的项,但保持原有的颜色、线型等美学效果。此前尝试用scale_colour_discrete(breaks = ...)虽成功移除目标项,但触发了默认配色,修改配色后又导致虚线变为灰色。

解决方案

核心思路是直接在已有的scale_colour_manual中配置breaks参数,指定需要显示的图例类别,同时保留原有的颜色映射,既过滤图例项又不改变绘图样式。此外修正代码中的拼写错误,并补充缺失的变量定义。

修改后的完整代码

set.seed(123)

# 补充缺失的变量定义
maxTSA_height <- 0.6
pipe_height_m <- 0.3
pipe_base_m <- 0.25
pipe_top_m <- 0.35

# 生成数据集
season_df <- data.frame(
  t = 1:100,
  Q = c(rnorm(25, mean = 0.5, sd = 0.1), rnorm(25, mean = 0.4, sd = 0.1),
        rnorm(25, mean = 0.3, sd = 0.1), rnorm(25, mean = 0.2, sd = 0.1)),
  MRC = sample(c("Autumn", "Winter", "Spring", "Summer", "Autumn no pipe", "Winter no pipe", "Spring no pipe", "Summer no pipe"), 100, replace = TRUE)
)

# 设定因子水平顺序
season_df$MRC <-
  factor(season_df$MRC,
         levels = c("Autumn", "Autumn no pipe", "Winter", "Winter no pipe", "Spring", "Spring no pipe", "Summer", "Summer no pipe"))

# 保留原有配色方案
cbp2_pipe <- c("#E69F00", "#E69F00",
               "#56B4E9", "#56B4E9",
               "#009E73", "#009E73",
               "#F0E442", "#F0E442",
               "#000000")

plot <- season_df %>%
  ggplot(aes(
    x = t,
    y = Q,
    colour = MRC,
    # 修正拼写错误:soild → solid
    linetype = ifelse(grepl("no pipe", MRC), "solid", "dashed")
  )) +
  geom_line(size = 1) +
  labs(x = "Time (hours)",
       y = "TSA depth (m)") +
  geom_hline(
    yintercept = maxTSA_height,
    linetype = 'dashed',
    color = 'black') +
  # 在手动配色中指定需要显示的图例项
  scale_colour_manual(
    values = cbp2_pipe,
    breaks = c("Autumn", "Winter", "Spring", "Summer")
  ) +
  scale_linetype(guide = "none") +
  annotate("text", x = 50, y = (maxTSA_height + 0.015), label = "TSA full level", size = 8 / .pt) +
  annotate("text", x = 50, y = (pipe_height_m), label = "Outlet pipe", size = 8 / .pt) +
  theme_classic() +
  theme(
    plot.title = element_blank(),
    axis.text = element_text(size = 8),
    axis.title = element_text(size = 10),
    legend.title = element_blank(),
    legend.text = element_text(size = 8),
    legend.position = "top"
  ) +
  annotate("rect", xmin = -Inf, xmax = Inf, ymin = pipe_base_m, ymax = pipe_top_m, alpha = .1)

plot

关键修改点

  • 过滤图例但保留配色:在scale_colour_manual中添加breaks参数,仅指定需要显示的季节类别,颜色映射依然使用自定义的cbp2_pipe,不会触发默认配色。
  • 修正线型拼写错误:将soild改为solid,避免因ggplot无法识别线型导致的异常显示。
  • 移除冲突函数:删除重写的scale_colour_discrete函数,避免与手动配色设置冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:03:14