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:
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:
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.
you simply need to edit the heights of the gtable,
Edit: with the more specific instructions, I'd suggest a different strategy: add the first panel only to the gtable of the second plot,