Aligning and arranging charts in ggplot

前端 未结 1 683
借酒劲吻你
借酒劲吻你 2021-01-21 23:33

I have two plots in ggplot with similar ranges on the axis that I would like to align.

Using:

library(grid)
grid.newpage()
grid.draw(rbind(ggplotGrob(g1)         


        
相关标签:
1条回答
  • 2021-01-22 00:02

    you simply need to edit the heights of the gtable,

    library(ggplot2)
    library(grid)
    g1 <- g2 <- ggplotGrob(qplot(1,1))
    
    g <- rbind(g1,g2,size="last")
    id <- g$layout$t[g$layout$name == "panel"]
    g$heights[id] <- lapply(c(1,4), "unit", "null")
    grid.newpage()
    grid.draw(g)
    

    Edit: with the more specific instructions, I'd suggest a different strategy: add the first panel only to the gtable of the second plot,

    p1 <- ggplot(df1)+geom_point(aes(x=x,y=y))
    p2 <- ggplot(df2)+geom_text(aes(x=x,y=0,label=r),angle=45,size=2)
    snug <- theme_bw() + theme(plot.margin=unit(c(0.5,0.5,0,0),"line"))
    
    library(gtable)
    g1=gtable_filter(ggplotGrob(p1 + snug), pattern = "panel", trim = TRUE, fixed=TRUE)
    g2=ggplotGrob(p2 + snug)
    
    g <- g2
    g <- gtable_add_rows(g, unit(0.2, "null"), 0)
    g <- gtable_add_grob(g, g1, 1, 4)
    grid.newpage()
    grid.draw(g)
    

    enter image description here

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