ggplot存在两个图例时Limit线条图例框颜色异常如何解决
你遇到的这个异常是因为fill = Brand被定义在ggplot()的全局美学映射中,所有图层默认继承该映射。当条形图图例开启后,geom_hline生成的Limit图例也会应用fill映射规则,导致图例背景被填充了品牌对应的颜色,不符合预期。
下面是两种可行的解决方法:
方法1:将fill映射迁移到geom_bar图层(最推荐)
将仅属于条形图的fill映射从全局移除,避免其他图层继承冲突,修改后完整代码如下:
library(ggplot2) df <- data.frame( Input = c("S1", "S2", "S3", "S4"), Brand = c("Brand01", "Brand01", "Brand01", "Brand01", "Brand02","Brand02","Brand02","Brand02"), Average = c(21.52027, 21.60699, 20.77871, 21.22759, 25.05574, 22.74372, 22.80795, 22.98509), Limit = c(31.89098, 31.89098, 31.89098, 31.89098, 31.57953, 31.57953, 31.57953, 31.57953)) p = ggplot(df, aes(x=Input, y=Average)) + facet_wrap(~ Brand, ncol = 2) + # fill映射移到geom_bar内部,仅对当前图层生效 geom_bar(aes(fill=Brand), stat="identity", position=position_dodge(), colour="black", width = 0.9, show.legend = TRUE) + xlab("Input") + ylab("Average") + theme(axis.title.x = element_text(size=14), axis.title.y = element_text(size=14), legend.text = element_text(size=14), plot.title = element_text(size = 20, face = "bold"), axis.text.x = element_text(size=6))+ theme(axis.text.x = element_text(angle = 90)) + geom_hline(aes(yintercept=Limit, linetype = "dashed"), color = "red") + scale_linetype_manual(name = "Limit", values = "dashed", labels = "") p
方法2:手动重置Limit图例的填充样式
如果你需要保留全局的fill映射,可以通过guides函数单独覆盖linetype图例的填充属性,强制设置为白色,只需在原有代码末尾添加一行即可:
# 原有代码不变,新增下面这行 p + guides(linetype = guide_legend(override.aes = list(fill = "white")))
两种方法都可以让Limit图例的背景恢复为正常的白色/灰色效果,同时保留品牌图例的正常显示。
内容的提问来源于stack exchange,提问作者jkinstack
相关产品推荐
相关产品推荐

