[R] Legend help needed

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Mon Nov 15 12:39:30 CET 2004


You have not called legend() in your codes below, so we do not know what
your problem is. See other comments below.

On Mon, 2004-11-15 at 01:08, Sean David Richards wrote:
> R : Version 1.9.1
> 
> Hi,
> 
> Am having trouble adding a legend to scatterplot. R code is shown below. 
> I have tried various incantations to add a legend (using the legend() 
> function) to the resulting plot but without any success. Looks like it 
> should be simple but I must be missing something. Any pointers would be 
> welcome.
> Have looked at help(legend) etc.

help(legend) provides many nice examples. Here is a simplified one :

x <- seq(-pi, pi, len = 65)
plot(x, sin(x), type="l", lty=1, col=1)
lines(x, cos(x), type="l", lty=2, col=2)
legend(-pi, 1, legend=c("sin", "cosine"), lty=1:2, col=1:2)

Or you can replace the last line with 
 legend(locator(1), legend=c("sin", "cosine"), lty=1:2, col=1:2)
where the legend will be placed on mouse left click.

> --8<----------------------------------------------------------------------
> ---
> 
> sfiles <- c("72_12_12_V.csv ",
>             "150_25_15_V.csv",    
>             "150_25_20_V.csv",    
>             "150_25_25_V.csv",    
>             "150_25_40_V.csv",    
>             "150_25_60_V.csv",    
>             "150_25_90_V.csv",    
>             "240_40_40_V.csv")                  
>             
> ## process each file in list
> for (i in 1:length(sfiles)) {
> data <- read.csv(paste("../data/",sfiles[i],sep=""))
> 
> ## assign columns to some nice names
> K <- data[,8]
> AN <- data[,3] * (data[,2] - data[,4])
> 
> ## plot K against AN

Please give a simplified example. You do not need to show us all the
preprocessing steps. It can be distracting.

> if ( i == 1) {
>     plot(AN, K, ylim=c(1000,9000), xlim=c(0,1500), 
>           xlab="Area above Notch (mm)",
>           main="Size Effect Specimens")
>     par(new=TRUE)                        
>     }
> else{
>     plot(AN,K, pch=(i),ylim=c(1000,9000), xlim=c(0,1500), 
>           axes=FALSE,xlab="")
>     par(new=TRUE)
>     }
> }

Have you considered points() or lines() here ? You could simplify to

plot(0,1000, type="n", xlim=c(0,1500), ylim=c(1000,9000),
     xlab="Area above Notch (mm)", main="Size Effect Speciments")

n <- length(sfiles)

for (i in 1:n) {
  data <- read.csv(paste("../data/",sfiles[i],sep="")) 
  K    <- data[,8]
  AN   <- data[,3] * (data[,2] - data[,4])

  points( AN, K, pch=i, col=i )
}

legend( 1500, 9000, legend=paste("Data from", sfiles), pch=1:n, col=i )

> --8<----------------------------------------------------------------------
> ---




More information about the R-help mailing list