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

如何去除ggplot2图例标签周围的方框?

解决ggplot2图例标签周围方框的问题

问题场景

我绘制了一张包含第一分位数和第三分位数ribbon的折线图,用ggplot2绘图时,图例标签周围出现了方框。尝试theme(legend.background=element_blank())或guides(guides_legend)覆盖等方法都没法去除。

数据集与绘图代码

mutate(code_range = fct_reorder2(code_range, year, order)) %>% 
  ggplot(aes(x=year, y=value, group=code_range, color=code_range)) +
  geom_ribbon(aes(ymin = min_range, 
                  ymax = max_range), fill = "grey70", alpha=0.1) +
  geom_line(size=1) +
  labs(title="Title", 
       subtitle=paste0("subtitle"),
       x="",y="",
       caption="Source") +
  scale_colour_manual(values = c("min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B", 
                                 "q3" = "#B5B5B5", "max" = "#878787")) +
  scale_fill_manual(values = c("min" = "#FFFFFF", "q1" = "#B5B5B5", "median" = "#27408B", 
                               "q3" = "#B5B5B5", "max" = "#878787")) +
  theme_opts +
  theme(legend.title = element_blank(), 
        legend.position = "bottom") +
  theme(legend.background=element_blank()) 
plot 

绘图效果

绘图结果

解决方法

你看到的方框是单个图例项符号的背景框,legend.background控制的是整个图例区域的背景,对它无效。需要修改legend.key的设置:

在theme()中添加legend.key = element_blank(),就能直接去除这些方框。

修改后的完整代码:

mutate(code_range = fct_reorder2(code_range, year, order)) %>% 
  ggplot(aes(x=year, y=value, group=code_range, color=code_range)) +
  geom_ribbon(aes(ymin = min_range, 
                  ymax = max_range), fill = "grey70", alpha=0.1) +
  geom_line(size=1) +
  labs(title="Title", 
       subtitle=paste0("subtitle"),
       x="",y="",
       caption="Source") +
  scale_colour_manual(values = c("min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B", 
                                 "q3" = "#B5B5B5", "max" = "#878787")) +
  scale_fill_manual(values = c("min" = "#FFFFFF", "q1" = "#B5B5B5", "median" = "#27408B", 
                               "q3" = "#B5B5B5", "max" = "#878787")) +
  theme_opts +
  theme(legend.title = element_blank(), 
        legend.position = "bottom",
        legend.background = element_blank(),
        legend.key = element_blank()) # 新增此行去除方框
plot 

如果想优化图例显示(避免color和fill图例重复),可以添加guides()设置合并图例:

guides(fill = guide_legend(override.aes = list(alpha = 0.3)), 
       color = guide_legend(override.aes = list(fill = NA)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:15:33