在一个带有相应图例的多面图上添加第二个 geom_layer

Add second geom_layer on only one faceted plot with corresponding legend

我正在使用第一个数据框创建多面图,然后向其中一个面板添加第二个 geom_point。我的问题是我想为添加的点显示相应的图例。

为了在我想要的面板上绘制第二个 geom_point,我创建了一个具有相应值的新 data frame 并修改了 River 列以绘制新的 [=13] =] 在正确的面板上,但图例不正确。我想在河流部分有一个蓝色的圆圈。感谢回复的人,我在 上学到了处理图例的新方法,但在这里它不起作用,因为这个情节是多面的。

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

这里是df1和df2的dput

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

虽然这没有回答编码问题,但它可能是可视化的解决方案。

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) 

reprex package (v2.0.0)

于 2021-04-12 创建