[R] ggplot2: how to increase size of legend box when converting to pdf

Ranjan Maitra maitra.mbox.ignored at inbox.com
Mon Mar 3 23:16:51 CET 2014


On Mon, 3 Mar 2014 16:17:11 -0500 Duncan Murdoch
<murdoch.duncan at gmail.com> wrote:

> On 14-03-03 4:02 PM, Ranjan Maitra wrote:
> > Hi,
> >
> > I have struggled with this quite a bit (all morning and afternoon) and I
> > am not sure I am any close to a solution. Basically, here is my sample
> > code:
> >
> > require(grid)
> > require(ggplot2)
> >
> > X <- data.frame(x = c(rnorm(10), rnorm(10, mean = 2, sd = 2), rnorm(10,
> > mean =5)), group = c(rep("Ellipse", 10), rep("PeakAmp", 10), rep
> > ("Rectangle", 10)))
> >
> >
> >
> > bp <- ggplot(data=X, aes(x=group, y=x, colour=group)) + geom_point() +
> > theme_bw()
> >
> > bp +  theme(legend.background = element_rect(fill = "white", color =
> > "black",                 size = 0.1, linetype="solid"), legend.key =
> > element_rect(fill = 'white', color = "white", size = 0.1),
> >                legend.text = element_text(size = 8),
> >                legend.key.height = unit(0.5, "cm"),
> >                legend.key.width = unit(0.5, "cm"),
> >                legend.justification=c(0.9,0.1), legend.position=c(0.9,
> > 0.1))
> >
> > dev.copy2pdf(file = "Rplots.pdf", height = 4, width = 6.5)
> >
> >
> > I get exactly what i want on the plotting device (x11). However, the
> > pdf has text spilling out of the legend box. I understand that this
> > could  be an issue of the viewer and the encoding but is there anything
> > I can do in R to reliably get around this issue in the plots
> > preparation stage?
> 
> Don't use dev.copy2pdf.  Use pdf() to open a PDF device at the 
> beginning, plot to it, then call dev.close().  This will do all the size 
> calculations using the pdf device.

Thank you!! This does work exactly as you say. (Only minor point: I do
not have dev.close() rather dev.off() on my linux system.)

> It's possible your text will still not fit; in that case, something in 
> your system is not measuring it properly, and there's not much R can do 
> to fix it.

Thankfully, at least for now, that does not seem to be an issue.

Many thanks again!

Best wishes,
Ranjan

>

____________________________________________________________
FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!




More information about the R-help mailing list