添加带可见SE区间的loess平滑后ggplot图例背景颜色异常问题
解决ggplot2显示SE区间后图例背景异常的问题
当启用geom_smooth的SE区间(se=TRUE)时,ggplot2会自动将fill美学与分组变量(此处为endroit)绑定,导致图例中出现SE区间的填充色块,覆盖了你设置的legend.key白色背景。以下是两种可行的解决方法:
方法1:覆盖图例中的fill属性
在现有代码基础上添加guides()函数,手动覆盖colour图例的fill样式为透明,以此露出预设的白色背景:
ggplot(dcomb, aes(x = DatHr, y = Radon, colour = endroit)) + theme_bw() + geom_line(alpha = 0.7) + geom_smooth(method = "loess", span = 0.2, se= TRUE) + theme( legend.position = "inside", legend.position.inside = c(0.8, 0.95), legend.justification.inside = c("center", "top"), legend.background = element_rect(fill = "white", colour = NA), legend.key = element_rect(fill = "white", colour = NA) ) + guides(colour = guide_legend(override.aes = list(fill = NA)))
方法2:单独控制geom_smooth的fill映射
如果需要保留SE区间的填充色,但不让fill生成额外图例,可以在geom_smooth中单独指定fill映射,同时隐藏fill图例:
ggplot(dcomb, aes(x = DatHr, y = Radon, colour = endroit)) + theme_bw() + geom_line(alpha = 0.7) + geom_smooth(aes(fill = endroit), method = "loess", span = 0.2, se= TRUE) + theme( legend.position = "inside", legend.position.inside = c(0.8, 0.95), legend.justification.inside = c("center", "top"), legend.background = element_rect(fill = "white", colour = NA), legend.key = element_rect(fill = "white", colour = NA) ) + guides(fill = "none")
两种方法均可实现:显示SE区间填充的同时,保持图例背景为白色、无额外填充色块的简洁样式。
内容的提问来源于stack exchange,提问作者Denis Chabot
相关产品推荐
相关产品推荐

