如何保留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
相关产品推荐
相关产品推荐

