[R] How to plot a legend centered only on the x axis
Jim Lemon
drjimlemon at gmail.com
Fri May 12 01:30:45 CEST 2017
Hi Antonio,
First you want the center of the plot:
xylim<-par("usr")
x_center<-sum(xylim[1:2])/2
Then as you want to have you legend above the plot:
# you will probably want to change the "20" to your preference
y_bottom<-xylim[4]+diff(xylim[3:4])/20
then:
legend(x_center,ybottom,...xjust=0.5,yjust=0)
Jim
On Fri, May 12, 2017 at 4:36 AM, Antonio Silva <aolinto.lst at gmail.com> 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.
>
> Antonio
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list