[R] trouble positioning legends on barplot written to a file

Uwe Ligges ligges at statistik.uni-dortmund.de
Tue Nov 12 23:55:57 CET 2002

Tom Arnold wrote:
> I'm trying to generate some plots for print publication and I'm having trouble
> getting them the way I want. I get a plot with a legend that overlaps the bars
> and looks bad. Also, I'm saving this as PDF file (whatever happened to the
> "png" function to save as PNG format, in r 1.4.1?)

??? pdf() produces PDFs, png() portable network graphics, etc. .... I
don't get the point.
BTW: R-1.4.1 is rather old.

> I've tried a number of things, which produce a number of questions.
> 1) it seems that the "legend" for a plot must be within the plot area. Is
> there a way to put the legend above, below, or to the side of the plot? The
> particular data I have fill up the plotting area (stacked bar charts, going to
> 100% in each bar)

 par(xpd = TRUE)
before legend(), see ?par for details.

> 2) I've tried using "locator()" to position the legend. This only works, so
> far, if I am not using trying to divert output to another device -- like
> creating a PDF via
> pdf();
> barplot(resultmat);
> dev.off();
> so if I take out the pdf() and the dev.off() and just do this:
> barplot(resultmat);
> legend(locator(1),legend=l,fill=colors);
> it works, on the graphics display device window on screen.
> However, if I do this:
> pdf(onefile=FALSE);
> barplot(resultmat);
> legend(locator(1),legend=l,fill=colors);
> dev.off();
> I get:
> >Error in legend(locator(1),legend = l : missing y
> Also it doesn't let me specify a point. I suppose that's not so surprising,
> because it is drawing to a non-interactive graphics device (the PDF "device"
> is non-interactive, right?), but the error message is confusing.

I wouldn't expect locator() to work that way at all ...

> So, is there any way to specify the location with locator() AND to save that
> plot to a file?

Yes. plot() to the windows() or x11() device, use locator() and "copy"
the plot to another device.
Look particularly at 
 ?dev.copy, ?dev.print, and ?dev.copy2eps(...)
I don't recommend this way.

> And if I don't use "locator' then I have to specify the legend location to
> "legend(x,y, legend) but the documentation doesn't say what coordinate system
> that's supposed to be in.

Use par("usr") (after barplot()) to get some interesting information.
Thgis can be combined with par(xpd = TRUE), which was mentioned above:

 pdf(onefile = FALSE)
 # get "extremes of the user coordinates of the plotting region." 
 # "plotting clipped to figure region"  
 par(xpd = TRUE)
 # now a proper legend()

Uwe Ligges

> TIA.
> Tom Arnold
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list