1

I like to include ggplots within a document which has a width of the main text area (one column) of 130 mm, followed by a margin of 7 mm to the right and an area for annotations (e.g. LaTex \mpar{}). The legend shoudl be placed in the annotations area. The problem I am facing is that the right edge of the panel is important in this setup since it defines the end of the main content (130mm) and the beginning of the legend (+7mm). I am aware of the sizing options ggsave() offers as well as positioning the legend using theme(). However, I do not fully understand the positioning and dimensions (this questions offers some assistance).

Is there a way to access dimensions in a more detailed way or is another plotting package more suitable?

Example plot with relevant dimensions in red (taken from this tutorial):

Example plot with relevant dimensions in red

fr3d-5
  • 792
  • 1
  • 6
  • 27

1 Answers1

0

It's a bit fiddly, even for single-panel plots, but with some work you can calculate the correct size and viewports,

library(ggplot2)
library(grid)

p <- qplot(1,1,color=1) + theme(plot.background = element_rect(fill=NA))
g <- ggplotGrob(p)

# get the width of guide and stuff on the right
id_guide <- g$layout$r[grep('guide',g$layout$name)]
gw <- convertWidth(sum(g$widths[id_guide:ncol(g)]), 'cm')

# make a new gtable with fixed panel width
g_fixed <- g
id_panel <- g$layout$l[grep('panel',g$layout$name)]
g_fixed$widths[id_panel] <- unit(130,'mm') - sum(g$widths[-(id_panel:ncol(g))])

grid.newpage()
# viewport smaller than device for illustration
vp <- viewport(width=unit(130,'mm'), height=0.8)
pushViewport(vp=vp)
grid.rect(gp=gpar(fill='gold',lty=2))
# within the current viewport, place fixed grob
g_fixed$vp <- viewport(x=0,width=unit(130,'mm')+gw, just = 'left')
grid.draw(g_fixed)

Related: Align panel.background instead of plot.background with document margins