Modify legend in facetted plot, ggplot2

前端 未结 1 2112
情歌与酒
情歌与酒 2021-02-11 00:29

For this graph, I want to split the legend into 2 separate legends. One showing the Pulsed Wetlands as circles with the shades corresponding to Wetland number and one showing t

相关标签:
1条回答
  • 2021-02-11 01:25

    Here is a solution inspired by this question

    First, made new variable colvec2 that contains all colors only once.

    colvec2 <-c("white", "gray80", "gray60", "gray37",  "black")  
    colvec <-c("white", "white","gray80", "gray80", "gray60", "gray60", "gray37", "gray37","black", "black")  
    

    Original plot saved as object and without the legend.

    p<-ggplot(water, aes(Date, Temp, group=Wetland, shape=Hydrology)) +
      geom_point(aes(color=Wetland),size=3) +
      scale_colour_manual(values=colvec) +
      facet_grid(Layer ~ Hydrology) +
      theme(legend.position="none")
    

    Plot that contains only data of Pulsed. Set shape=16 inside the geom_point(). With scale_colour_manual() changed legend title and colors.

    p1<-ggplot(subset(water,Hydrology=="Pulsed"), 
         aes(Date, Temp, group=Wetland, shape=Hydrology)) +
      geom_point(aes(color=Wetland),size=3,shape=16) +
      scale_colour_manual("Pulsed Wetlands",values=colvec2) +
      facet_grid(Layer ~ Hydrology)
    

    The same as p1, only for Static.

    p2<-ggplot(subset(water,Hydrology=="Static"), 
          aes(Date, Temp, group=Wetland, shape=Hydrology)) +
      geom_point(aes(color=Wetland),size=3,shape=17) +
      scale_colour_manual("Static Wetlands",values=colvec2) +
      facet_grid(Layer ~ Hydrology)
    

    Save plots p1 and p2 using ggplot_build() and ggplot_gtable().

    pt1<-ggplot_gtable(ggplot_build(p1))
    pt2<-ggplot_gtable(ggplot_build(p2))
    

    Extract just grob of legends for both plots. This time legends are in 12. element (element containing guide-box)

    leg1<-pt1$grobs[[12]]
    leg2<-pt2$grobs[[12]]
    

    Now use grid.arrange() and arrangeGrob() to plot all parts.

    library(gridExtra)
    grid.arrange(arrangeGrob(p,arrangeGrob(leg1,leg2), ncol = 2,widths=c(3/4,1/4)))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题