3

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:

The data and colors used here are used for illustration purposes only

Sileo
  • 307
  • 2
  • 18

1 Answers1

5

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 = "")

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • 2
    You defeated me by seconds. That deserves +1 As always you are awesome! – Duck Oct 14 '20 at 18:28
  • Damn simple. Thanks. Any idea on why it isn't the default behaviour ? – Sileo Oct 14 '20 at 18:28
  • What if I want to add a legend for the points too ? Ideally to obtain "Model : -LM -Loess" and "Data: -points". I feel like this answer makes it harder to achieve – Sileo Oct 14 '20 at 20:00
  • 1
    Not at all @Rphad - you could add a shape, size or alpha scale to do that. I'll update to demonstrate – Allan Cameron Oct 14 '20 at 20:26
  • I was trying with colour inside aes() for coloured data points but this works well. Thanks again ! – Sileo Oct 14 '20 at 20:37