[R] Legend placement in barplots

Uwe Ligges ligges at statistik.uni-dortmund.de
Mon Jan 7 19:52:40 CET 2002


david.whiting at ncl.ac.uk wrote:
> 
> Hi,
> 
> I am trying to use R to create some reasonably automatic output for
> routine monitoring. Some of these outputs are simple bar charts. I need to
> create something similar to an excel bar chart (yuk!, I know...:) which
> places the legend at the bottom of the chart.
> 
> barplot() place the legend over the chart and can potentially cover some
> of the detail (especially if the bars are numerous and thin). legend()
> allows me to position the legend but, as the example below shows, still
> only within the chart area. How can I place the legend below or to the
> right of a bar plot? Do I need to use plot.new() and build it up myself?
> 
> Example:
> --------
> barplot(1:3, legend.text = c("cats", "dogs", "cows"))
> legend(1,0.5, c("cats", "dogs", "cows"))
> legend(1,0.1, c("cats", "dogs", "cows"))

The solution is to play around with the magic of par():

 par("mar")	# borders, see ?par
  # [1] 5.1 4.1 4.1 2.1
  # Now increase size of the bottom-border:
 par(mar=c(10.1, 4.1, 4.1, 2.1))
  # And set cpd=TRUE, so all plotting is clipped to the figure 
  # (not the plot) region:
 par(xpd=TRUE)
  # Your barplot:
 bp <- barplot(1:3) 
  # Text for the legend:
 legend.text <- c("cats", "dogs", "cows")
  # And plot the legend below the existing plot:
 legend(1,-0.5, legend.text, fill=heat.colors(length(legend.text)))
  # Or much nicer, center the legend:
 legend(mean(range(b)), -0.5, legend.text, xjust = 0.5,
	fill=heat.colors(length(legend.text)))

Uwe Ligges
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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