[R] How to center a horizontal legend with specified 'text.width'

Jim Lemon jim at bitwrit.com.au
Mon May 13 00:47:56 CEST 2013


On 05/12/2013 09:47 PM, Sascha Wolfer wrote:
> Hello dear list,
>
> I just cannot figure out how to do this and didn't find a solution for my specific problem.
>
> I want to place a centered horizontal legend between 4 plots. That's no problem.
>
> The problem is: As soon as I specify the "text.width" parameter to separate the two legend entries, the legend is not centered anymore. I thought the 'xjust' parameter would do what I want, but it doesn't change a thing :(
>
> Please see this minimal example:
>
> # Setting up the layout of plots
> layout(matrix(c(1,2,3,3,4,5), nrow = 3, byrow = T), heights = c(1,0.1,1))
> par(mar = c(4.3,4,2,1.5))
> # plot 1
> plot(rnorm(100))
> # plot 2
> plot(rnorm(100))
> # legend as plot no.3
> par(mar = c(0,0,0,0))
> plot.new()
> legend(x = "center", lty = c("solid", "dashed"), horiz = T,
>        legend = c("Beginning", "End"), lwd = 2, bty = "n", text.width = 0.2)
> par(mar = c(4.3,4,2,1.5))
> # plot 4
> plot(rnorm(100))
> # plot 5
> plot(rnorm(100))
>
Hi Sascha,
It's a rather nasty kludge, but you might be able to use this:

legend(x="center",lty=c("solid",NA,"dashed"),horiz=TRUE,
  legend=c("Beginning","         ","End"),lwd=2,bty="n")

Jim



More information about the R-help mailing list