Mixed fill color in ggplot2 legend using geom_smooth() in R

一曲冷凌霜 提交于 2020-12-04 02:44:43

问题


When plotting two regression curves using geom_smooth() in ggplot2, for the fill color, the legend picks the one where the confidence intervals intersect. I do think this behaviour arises when the overlapping area is proportionally bigger that the other, however I find this quite undesired because the reader is capable of deducing that the "darkened" area is the one where the CI intersect. It is IMHO a bit harder or unintuitive to assign the same color for both the curves.

How can I correct this ?

MWE:

library(ggplot2)

p <- ggplot(data=iris, aes(x=Sepal.Width, y=Sepal.Length)) + geom_point()
p <- p + geom_smooth(method=loess, aes(colour="Loess"), fill="yellow")
p <- p + geom_smooth(method=lm, aes(colour="LM"))

print(p)

Output:


回答1:


You can add the fill as an aesthetic mapping, ensuring you name it the same as the color mapping to get legends to merge:

library(ggplot2)

ggplot(data=iris, aes(x=Sepal.Width, y=Sepal.Length)) +
  geom_point(aes(shape = "data")) +
  geom_smooth(method=loess, aes(colour="Loess", fill="Loess")) +
  geom_smooth(method=lm, aes(colour="LM", fill = "LM")) +
  scale_fill_manual(values = c("yellow", "gray"), name = "model")  +
  scale_colour_manual(values = c("red", "blue"), name = "model") +
  labs(shape = "")



来源:https://stackoverflow.com/questions/64359233/mixed-fill-color-in-ggplot2-legend-using-geom-smooth-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!