Search code examples
rggplot2smoothingpolynomials

How to add a legend for different `stat_smooth` lines and how to place it in the upper-left corner?


I have the next plot:

enter image description here

Plot<- ggplot(df1,aes(x=RMS.V13AP, y=RMS.X16,colour=ID)) + 
  geom_point(size=1) +
  coord_capped_cart(bottom="both",left="both") +
  theme_bw() + 
  labs(x=expression(Acoustic~activity~(m.s^{-2})),y=expression(Real~activity~(m.s^{-2}))) + 
  theme(strip.background=element_blank(),
        axis.title.x =element_text(margin = margin(t = 2, r = 20, b = 0, l = 0),size = 16),
        axis.title.y =element_text(margin = margin(t = 2, r = 20, b = 0, l = 0),size = 16),
        axis.text.x = element_text(angle = 0, hjust = 0.5,size = 12),
        axis.text.y = element_text(angle = 0, hjust = 0.5,size = 14),
        strip.text.x = element_text(size = 14),
        strip.text.y = element_text(size = 13),
        axis.line = element_line(),
        panel.grid.major= element_blank(),
        panel.grid.minor = element_blank(),
        legend.text=element_text(size=12),
        legend.title = element_text(size=12, face = "bold"),
        legend.key=element_blank(),
        legend.position = "top",
        panel.border = element_blank(),
        strip.placement = "outside") +
  scale_x_continuous(breaks=c(0,0.025,0.050,0.075,0.095)) +
  guides(color=guide_legend(override.aes=list(fill=NA),nrow = 1 ))
Plot

Plot <-Plot + stat_smooth(method = "lm",formula= y ~ x, se=FALSE,colour="lightblue") +
  stat_smooth(method = "lm",formula= y ~ x + I(x^2), se=FALSE,colour="skyblue2")  +
  stat_smooth(method = "lm",formula= y ~ x + I(x^3), se=FALSE,colour="steelblue2")  +
  stat_smooth(method = "lm",formula= y ~ x + I(x^4), se=FALSE,colour="royalblue1")  +
  stat_smooth(method = "lm",formula= y ~ x + I(x^5), se=FALSE,colour="blue4") 
Plot

I would like to indicate which kind of degree polynomial is each line. However, I don't know how to include a legend with this info. I also wonder If I could place the legend in the area of the plot where there are no points (upper-left corner).


Solution

  • You could use the ggnewscale package to map multiple variables to the same aesthetic (colour). However, this makes the legend placement a bit weird, so I don't know how to place it correctly. Here is an example with the mtcars dataset.

    library(ggplot2)
    library(ggnewscale)
    
    ggplot(mtcars, aes(disp, mpg)) +
      geom_point(aes(colour = as.factor(vs))) +
      scale_colour_discrete() +
      new_scale_color() +
      stat_smooth(method = "lm",formula= y ~ x + I(x^2),
                  aes(colour = "x^2"), se = FALSE) +
      stat_smooth(method = "lm",formula= y ~ x + I(x^3),
                  aes(colour = "x^3"), se = FALSE) +
      stat_smooth(method = "lm",formula= y ~ x + I(x^4),
                  aes(colour = "x^4"), se = FALSE)
    

    Created on 2020-05-01 by the reprex package (v0.3.0)