Aligning and arranging charts in ggplot

2019-02-25 18:13发布

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), ggplotGrob(g2), size = "last"))

where size='last' ensures the grids are aligned for x, I get a layout such as this:

enter image description here

The top chart has an excessive vertical range for the simple row I want to depict.

I would like to have an image more in keeping with the following:

enter image description here

Or alternatively, with the g1 chart aligned below the axis of the g2 chart. (For generality, let's say I want to be able to choose either, or even overlay g1 on top of g2.

(My original model was a single chart with the g1 component simply set as a layer in the g2 chart with y=0; however, the chart is too cluttered to read with that layout, so I thought I should move the original y=0 elements into a separate panel (i.e. g1).

Minimal Example:

size=50
df1=data.frame(x=seq(1,size),y=sample(-100:100,size,rep=TRUE))
df2=data.frame(x=seq(1,size),r=replicate(size,paste(sample(c(letters, LETTERS),3),collapse='')))
g1=ggplot(df1)+geom_point(aes(x=x,y=y))
g2=ggplot(df2)+geom_text(aes(x=x,y=0,label=r),angle=45,size=2)
library(grid) 
grid.newpage()
grid.draw(rbind(ggplotGrob(g1), ggplotGrob(g2), size = "last"))

I want the label strip (g2) to be positioned neatly with respect to the scatterplot. The g2 strip was part of the original chart as a geom_text() element at y=0 but the chart was too cluttered around there with the labels placed there too.

标签: r ggplot2 gtable
1条回答
家丑人穷心不美
2楼-- · 2019-02-25 18:42

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

查看更多
登录 后发表回答