Search code examples
rraster

How to represent certain values in a file as we want?


I have a raster file(1440*720 rows) contains values of 1 ,2 , and 3. when I plot the file , I got a map of three colors but I do not know which is which. How can I put those colors as as I want :

   1=red
   2=blue
   3=green

code:

pvm <- file("C:\\User_sm-das.bin","rb")
cor1<- readBin(pvm, numeric(), size=4,  n=1440*720, signed=TRUE)
r <-raster(t(matrix((data=cor1), ncol=720, nrow=1440)))
image(r)

Solution

  • You can use image.plot from fields which add a legend to the image. Here an example :

    First I generate some data :

    set.seed(1234)
    x<- 1:5; y<- 1:5
    z<- matrix(sample(c(1,2,3),25,rep=TRUE),ncol=5,byrow=TRUE)
    

    Then using fields you can have this , it uses the usual image parameters adding a legend.

    # fields 
    library(fields)
    image.plot(x,y,z,col = c("blue" , "red" ,"yellow"),
               interpolate=TRUE) 
    

    enter image description here

    Note that if you want to convert your raster matrix to a matrix of color you can do something like this :

    ## raster 
    r <- raster(ncol=5, nrow=5)
    values(r) <- z
    mm <- matrix(c("blue" , "red" ,"yellow")[values(r)],
                 ncol=5,byrow=TRUE)
    
         [,1]     [,2]   [,3]   [,4]     [,5]    
    [1,] "blue"   "red"  "red"  "red"    "yellow"
    [2,] "red"    "blue" "blue" "red"    "red"   
    [3,] "yellow" "red"  "blue" "yellow" "blue"  
    [4,] "yellow" "blue" "blue" "blue"   "blue"  
    [5,] "blue"   "blue" "blue" "blue"   "blue"  
    

    The problem with image you can't plot a mtrix of colors you need to have numeric values. But you can use grid.raster from grid package:

    library(grid)
    grid.raster(mm,interpolate=FALSE)
    

    EDIT

    To fix a legend manually you can play with axis.args argument of plot.image

       ## fields 
    image.plot(x,y,z,
               col = c("red" , "green" ,"blue"),
               axis.args=list( at=0:3, labels=0:3 ))