[R] How to plot a legend centered only on the x axis

Marc Schwartz marc_schwartz at me.com
Fri May 12 03:59:29 CEST 2017


> On May 11, 2017, at 7:01 PM, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
> 
> On 11/05/2017 2:36 PM, Antonio Silva wrote:
>> Hello r-users
>> 
>> I want to plot some barplots inside a looping with the legend placed
>> outside the plotting area.
>> 
>> No matter the number of bars I want the legend to be placed centered on the
>> x-axis.
>> 
>> See the example below
>> 
>> for(i in 1:10) {
>> var_1 <- sample(1000:100000,sample(3:8,1))
>> ymax <- max(var_1)
>> b<-barplot(var_1,col="blue")
>> var_2 <- sample(1000:ymax,length(var_1))
>> lines(rowSums(b),var_2,type="o",col="red",pch=16)
>> par(xpd=TRUE)
>> legend(*1.1*
>> ,ymax*-0.072,c("var_1","var_2"),horiz=T,cex=1.3,bty="n",pch=c(15,16),col=c("blue","red"),lty=c(0,1),lwd=c(0,2),pt.cex=2)
>> readline(prompt="Press [enter] to continue")
>> }
>> 
>> What I should use as x position in legend(x,y, ...), instead of *1.1*, to
>> have the legend centered on the x-axis?
>> 
>> I would love to use something like legend(x="center",y=ymax*-0.072, ... but
>> it did not worked.
>> 
>> I appreciate any suggestions. Best regards.
> 
> Instead of "center", use "top" or "bottom".  See the 2nd last example in examples(legend) for the possibilities.
> 
> If you want the legend outside the plotting area, set "inset" and "xpd" arguments.  For example,
> 
> plot(1,1)
> legend("top", pch = 1, legend = "point", inset = -0.1, xpd = TRUE)
> 
> 
> Duncan Murdoch


Bingo.

The 'inset' argument is what I was missing. That allows this to be done with one step, rather than the two that I had.

Thanks Duncan.

Marc



More information about the R-help mailing list