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

Antonio Silva aolinto.lst at gmail.com
Thu May 11 20:36:14 CEST 2017


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.

Antonio

	[[alternative HTML version deleted]]



More information about the R-help mailing list