Search code examples
rdplyrfacet-wrapgeom-point

Add second geom_layer on only one faceted plot with corresponding legend


I'm creating a faceted plot with a first data frame and I add a second geom_point to one of the panel. My problem is I would like to show the corresponding legend for the added point.

To plot the second geom_point on the panel I want, I created a new data frame with the corresponding value and I modified the River column to plot the new geom_point on the correct panel but then the legend is not correct. I would like to have a blue circle in the River section. I learnt a new way to deal with legend on another post, thanks to the people who replied, but here it doesn't work here since this plot is faceted.

enter image description here

df2        <- as_tibble(df1[5,])
df2$River = "Var"

ggplot(data = df1[df1$River != "Roya",], aes(x = Date_plot, y = W_norm, shape = River, col = Type)) +  
  geom_point(size = 3) + 
  scale_shape_manual(values = c(15, 18, 17, 16, 16)) +
  scale_colour_manual(values = c("chocolate1", "darkcyan"), guide = guide_legend(order = 2)) +  
  scale_y_continous("W*") +
  scale_x_date("Years") + 
  geom_point(data = df2, aes(x = Date_plot, y = W_norm, shape = River), colour = "cornflowerblue", size = 3, inherit.aes = F) +
  facet_wrap(vars(River)) 

Here are the dput of df1 and df2:

structure(list(River = c("Durance", "Durance", "Durance", "Durance", 
"Roya", "Var", "Drac", "Drac", "Drac", "Drac", "Var", "Var", 
"Mareta", "Mareta", "Mareta", "Mareta", "Var"), Type = c("Under restoration", 
"Target", "Under restoration", "Target", "Under restoration", 
"Under restoration", "Under restoration", "Target", "Under restoration", 
"Target", "Target", "Under restoration", "Under restoration", 
"Under restoration", "Target", "Target", "Under restoration"), 
    Date_plot = structure(c(17167, 17167, 15340, 15340, 17532, 
    12784, 14975, 14975, 17532, 17532, 15340, 17532, 12784, 15706, 
    12784, 15706, 15340), class = "Date"), W_norm = c(5.7321, 
    7.9454, 5.1023, 7.0228, 5.0938, 4.7277, 2.7783, 9.303, 7.0742, 
    7.297, 10.2625, 9.5448, 2.83, 5.0009, 3.1914, 3.2644, 4.5448
    )), row.names = c(NA, -17L), class = c("tbl_df", "tbl", "data.frame"
))

structure(list(River = "Var", Type = "Under restoration", Date_plot = structure(17532, class = "Date"), 
    W_norm = 5.0938), row.names = c(NA, -1L), class = c("tbl_df", 
"tbl", "data.frame"))

Solution

  • Although this does not answer the coding question it may be a solution to the visualisation.

    library(ggplot2)
    
    df1$River[5] = "Var"
    df1$Type[5] = "Roya, under restoration"
    
    ggplot(data = df1, aes(x = Date_plot, y = W_norm, col = Type)) +  
      geom_point(size = 3) + 
      scale_colour_manual(values = c("chocolate1", "darkcyan", "cornflowerblue")) +  
      labs(y = "W*",
           x = "Years") + 
      facet_wrap(~River) 
    

    Created on 2021-04-12 by the reprex package (v2.0.0)