I am trying to arrange 2 plots created using ggplot2
and would like the plots to be the size of a square and one next to the other, with the common legend next
I'm not sure what you expect for the output, but try this,
g = arrangeGrob(
arrangeGrob(p1 + coord_fixed() + theme(legend.position="none"),
p2 + coord_fixed() +theme(legend.position="none"),
main = textGrob("The main figure title is also small and hard to align left", x=0, hjust =0, vjust=1, gp = gpar(fontsize = 22)), nrow=1),
mylegend, widths=unit.c(unit(1, "npc") - sum(mylegend$width),
sum(mylegend$width)), nrow=1)
ggsave("layout.pdf", g, width=12, height=5)
Add a theme()
to each plot and set the size of the elements you want to change, e.g
theme( axis.text.x=element_text(size=20) , axis.title.x = element_text(size = 20 , colour = "red" ) )
You can try arranging things on a grid page using pushViewport
to manually set the viewports like so, but you will probably have to play around with it a bit to get it exactly how you want:
grid.newpage()
# Create a grid arangement of viewports to 'put' the plots into...
# widths and heights are normalised parent coordinates which scale from 0 to 1 with 1 being the entire width of the plot page
# The respect argument forces widths and heights to respect each other as they are set
pushViewport( viewport( layout = grid.layout( 2 , 3 , heights = unit( c( 0.02 , 0.45 ) , "npc" ) , widths = unit( c( 0.4 , 0.4 , 0.1 ) , "npc" ) , respect = matrix(rep(1,6),2) ) ) )
# We print plots to particular 'cells' on our page specified by the layout.pos.row and layout.pos.col
print( p1 + theme(legend.position="none") , vp = viewport( layout.pos.row = 2 , layout.pos.col = 1 ) )
print( p2 + theme(legend.position="none") , vp = viewport( layout.pos.row = 2, layout.pos.col = 2 ) )
# The grid.text is output to row one, and breaks across columns 1:2
grid.text("The main figure title is also small and hard to align left" , just = "left" , x = unit(0.01, "npc"), y = unit(0.5, "npc"), vp = viewport( layout.pos.row = 1, layout.pos.col = 1:2) )
# We use upViewport to go up a level to the parent viewport
upViewport(0)
# We then define a new viewport for the legend which is a table grob.
# I had difficulty with this one so we set x and y coordinates and make it narrow but tall (0.1 npc width and 0.75 noc height)
vp3 <- viewport( width = unit(0.1,"npc") , height = unit(0.75 ,"npc") , x = 0.93, y = .5)
# We then activate this viewport
pushViewport(vp3)
# we output the legend which is a tableGrob to this viewport
grid.draw( mylegend )
popViewport()