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

如何保留geom_col()并移除ggplot图例颜色图标后的灰色背景?

解决方法

1. 移除geom_col(color映射)图例的灰色背景

用geom_col()映射color时,图例默认显示带灰色填充的矩形(柱形图的默认图例符号是填充矩形)。要去掉灰色背景,通过guides()强制图例填充为透明即可:

示例代码:

library(ggplot2)

# 构造示例数据
set.seed(123)
df <- data.frame(
  date = seq.Date(as.Date("2023-01-01"), as.Date("2023-01-10"), by = "day"),
  Precipitation = runif(10, 0, 5),
  Inflow = runif(10, 10, 20)
)

# 绘图并移除图例灰色背景
ggplot(df, aes(x = date)) +
  geom_col(aes(color = "Precipitation", y = Precipitation), fill = NA) + # 柱形仅保留边框(若需柱形有填充,可删除此fill参数)
  geom_line(aes(color = "Inflow", y = Inflow), linewidth = 1) +
  scale_color_manual(values = c("Precipitation" = "blue", "Inflow" = "red")) +
  guides(color = guide_legend(override.aes = list(fill = NA))) # 清空图例的填充背景

2. 改用fill aesthetic时让图例显示线条样式

若用fill映射降水数据,默认图例是填充方块,要改成线条样式,可通过guide_legend()的key_glyph参数指定图例符号为线条,同时调整样式:

示例代码:

ggplot(df, aes(x = date)) +
  geom_col(aes(fill = "Precipitation", y = Precipitation)) +
  geom_line(aes(color = "Inflow", y = Inflow), linewidth = 1) +
  scale_fill_manual(values = "blue") +
  scale_color_manual(values = "red") +
  # 将fill图例的符号改为线条
  guides(fill = guide_legend(key_glyph = "path", override.aes = list(color = "blue", fill = NA))) +
  # 可选:合并两个图例(设置相同的图例名称即可)
  labs(color = "Data Series", fill = "Data Series")

如果希望简化操作,更推荐统一用color映射(即第一个方案的写法),直接把柱形的填充设为透明,既能保留geom_col(),又能让图例默认显示线条样式,无需额外调整图例符号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:24:53