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

在ggplot图例中移除累计值分组并保留美学属性,自定义标签

问题描述

在同一张ggplot图表中同时展示年度学时(school hours)和累计学时(total school hours),已实现基础绘图,但需要优化图例:

  • 移除与累计值相关的三个分组的图例项
  • 仅保留对应区域的自定义标签“NW, G8”“NW, G9”“CA”
  • 保留这些累计值线条的颜色美学属性

此前尝试用scale_color_manual设置breaks后,累计值线条变为灰色,无法保留原颜色。

解决方案

核心是在颜色映射中明确指定需要显示的图例项、自定义标签,同时确保所有分组的颜色都被覆盖,避免未指定的分组自动变为灰色。

修改后的完整代码:

require(tidyverse)

## 学时对比:美国加州(CA) vs 德国北威州(NW)
df_hours <- data.frame(year=c(1:13),
                       hours_nw_G8=c(21.5,22.5,25.5,26.5,31.5,31.5,32.5,32.5,33.5,34,34,34,NA),
                       hours_nw_G9=c(21.5,22.5,25.5,26.5,28,29,30,30,31,31,31.5,29.5,29.5),
                       hours_ca=c(840,840,840,900,900,900,900,900,1080,1080,1080,1080,NA)
                       )
df_hours$hours_nw_G8 <- df_hours$hours_nw_G8 * 38 * 0.75 # 按周数及德国学时标准换算
df_hours$hours_nw_G9 <- df_hours$hours_nw_G9 * 38 * 0.75

# 计算累计学时
df_hours$c_hours_nw_G8 <- cumsum(df_hours$hours_nw_G8) / 8 # 累计后除以换算系数
df_hours$c_hours_nw_G9 <- cumsum(df_hours$hours_nw_G9) / 8
df_hours$c_hours_ca <- cumsum(df_hours$hours_ca) / 8

# 重塑数据并标记年度/累计属性
df_hours <- gather(df_hours, state, hours, hours_nw_G8:c_hours_ca, factor_key=TRUE)
df_hours$cu <- c(rep("annual",13*3),rep("cumulative",13*3))


# 绘图
ggplot(df_hours, aes(x=year)) +
  geom_line(aes(y=hours, color=state, linetype=cu), linewidth = 1) +
  scale_y_continuous(limits = c(0,1500), expand = c(0,0),
                     breaks = c(0,250,500,750,1000,1250,1500),
                     name="Hours (annual)",
                     sec.axis = sec_axis(~ .*8, name = "Hours (cummulative)",
                                         breaks = c(0,2000,4000,6000,8000,10000,12000))
                     ) +
  scale_x_continuous(limits = c(0.5,13.5), expand = c(0,0), breaks = c(1:13)) +
  labs(x="School Year", y="Hours") +
  theme_tufte() +
  # 关键修改:指定图例显示的分组、自定义标签,同时保留所有分组的颜色映射
  scale_color_manual(
    values = c("#073B4C", "#118AB2", "#FFD166", "#073B4C", "#118AB2", "#FFD166"),
    breaks = c("hours_nw_G8", "hours_nw_G9", "hours_ca"),
    labels = c("NW, G8", "NW, G9", "CA")
  ) +
  theme(axis.line = element_line(linewidth = 0.75), text = element_text(size = 10, color = "black"),
        legend.position = c(.3, .9), legend.title = element_blank()) + 
  guides(linetype = F)
关键修改说明
  • breaks:只保留年度学时的三个分组,过滤掉累计值分组,不让它们出现在图例中
  • labels:把原始的分组名称替换成用户需要的自定义标签
  • values:保持6个颜色的赋值顺序,确保累计值线条和对应年度分组用同一种颜色,避免变成灰色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:30:46