R: How do I use coord_cartesian on facet_grid with free-ranging axis

前端 未结 3 1285
礼貌的吻别
礼貌的吻别 2020-12-01 18:26

Consider some facet_grid plot

mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() 
mt + facet_grid(vs ~ am, scales = \"fr         


        
3条回答
  •  不知归路
    2020-12-01 19:29

    Old post but i was looking for the same thing and couldn't really find anything - [perhaps this is a way Set limits on y axis for two dependent variables using facet_grid()

    The solution is not very elegant/efficient but i think it works - basically create two plots with different coord_cartesian calls and swap over the grobs.

    # library(ggplot2)
    # library(gtable)
    
    # Plot
    mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() 
    
    # --------------------------------------------------------------------------------
    
    
    p1 <- mt + facet_grid(vs ~ am, scales = "free") + coord_cartesian(ylim = c(1,6))
    g1 <- ggplotGrob(p1)
    
    p2 <- mt + facet_grid(vs ~ am, scales = "free") + coord_cartesian(ylim = c(3,5))
    g2 <- ggplotGrob(p2)
    
    # ----------------------------------------------------------
    # Replace the upper panels and upper axis of p1 with that of p2
    # Tweak panels of second plot - the upper panels
    g1[["grobs"]][[6]] <- g2[["grobs"]][[6]]
    g1[["grobs"]][[8]] <- g2[["grobs"]][[8]]
    
    #Tweak axis
    g1[["grobs"]][[4]] <- g2[["grobs"]][[4]]
    
    grid.newpage()
    grid.draw(g1)
    

提交回复
热议问题