R: positioning of the legend and length of the lines in the legend

10,976

As pointed out in the comments restarting an R session and using

legend("topright",col=c("blue", "red"), lwd=2,
 legend=c("signal","std dev"), cex=0.85, bty="n", xjust=1, seg.len=0.5)

solved my problems.

Share:
10,976
Irene
Author by

Irene

Recent Graduate. Now young Analyst.

Updated on June 15, 2022

Comments

  • Irene
    Irene almost 2 years

    I can't set the location of the legend properly, I have tried to play around with xjust and ncol but it still appears in the middle of the graphic.

    Can you help it align it to the border (left or right I do not care)?

    Moreover is it possible to draw shorter lines in the legend? These appear too long.

     par(mar=c(5,4,4,5)+.1)
     plot(1:109,rnorm(109), type="l",col="blue", lwd=2, 
          main="Compare signal and std deviation MC3 ch44",
          ylab="signal", xlab="locations")
     par(new=TRUE)
     plot(1:109, rnorm(109), ylab="",xlab="", type="l", 
          col="red",xaxt="n",yaxt="n", lwd=2)
     axis(4)
     mtext("std. deviation",side=4,line=3)
     legend("topright",col=c("blue", "red"), lwd=2,
            legend=c("signal","std dev"), cex=0.85, bty="n", xjust=1)
    
  • Carl Witthoft
    Carl Witthoft over 10 years
    It is often true that legends and text will show up in the "wrong" place if you change the plot window size after plotting. Best to set the window size first if you want a specific aspect ratio. E.g. dev.new(width=3,height=9)