user3036416
user3036416

Reputation: 1255

Colours plot vector based

I have a vector z like this

z <- as.numeric(as.factor(c("A","B","C","D","E","F","G","H")))

and for different days a data frame df like this

df[[1]]

    ID     LON     LAT

    A     1        1
    B     10        14
    C     12        13

df[[2]]

    ID     LON     LAT

    A     2         3
    B     11        18
    D     12        13

df[[3]]

    ID     LON     LAT

    A     13        1
    E     10        14
    D     12        13

where the IDs are the ones in z but can be different for every day.

I have assigned a colour to each element of the vector

range01 <- function(x)(x-min(x))/diff(range(x))
rainbow(7)
cRamp <- function(x){
  cols <- colorRamp(rainbow(7))(range01(x))
  apply(cols, 1, function(xt)rgb(xt[1], xt[2], xt[3], maxColorValue=255))
} 

and what I would like to do is to plot for every day my df with the colours cRamp(z) but I am no able to link the ID value in every df with the one in z

Here is my code

for (i in 1:length(myfiles)){

  plot(df[[i]]$LON,df[[i]]$LAT, col = cRamp(z))
  map(add=T,col="saddlebrown",interior = FALSE)
  legend("topleft", legend=c(unique(df[[i]]$ID)), col=cRamp(z))
}

but the colour for e.g. ID A are not the same for every day!

Many thanks

Upvotes: 0

Views: 159

Answers (1)

Roland
Roland

Reputation: 132676

Maybe something like this:

z <- LETTERS[1:7]

df <- list(
  data.frame(ID=LETTERS[1:3],
             LON=c(1,10,12),
             LAT=c(1,14,13)),
  data.frame(ID=LETTERS[3:5],
             LON=c(2,11,18),
             LAT=c(2,9,20))
  )


layout(t(1:2))
for (i in 1:2){  
  plot(df[[i]]$LON, df[[i]]$LAT, 
       col = rainbow(length(z))[match(df[[i]]$ID,z)], 
       pch=16)
  legend("topleft", 
         legend=z, 
         col=rainbow(length(z)),
         pch=16)
}

enter image description here

Upvotes: 1

Related Questions