3

I wonder if it is possible to assign specific colors to the cells of a raster in r.

I know that “rasterize” in the package "raster" allows transferring values to a raster given the coordinates of the given value. However, I wonder if is possible to transfer just a color to the specific position of a cell?

In short, I have a given raster and an external database with three columns (x, y, and color). I would like to transfer the color in the third column to the cell in the raster at the x-y position.

This is the code that I have:

library(raster)

BaseRaster<-raster(xmn=1, xmx=4, ymn=1, ymx=4,resolution=1) #create an empty raster

Database<-data.frame(Xcols=c(1.5, 2.5,3.5,   1.5, 2.5,3.5,  1.5, 2.5,3.5) ,
Ycols= c(1.5, 1.5,1.5,   2.5, 2.5,2.5,  3.5, 3.5,3.5),
Cols=c("#FFF423","#FFFF14","#FFE20F","#FFF80A","#FFCB07","#FFE100","#FFEE0B","#FDEE0A","#FFE209"))

The question is how do I transfer the colors in the third column of the database to the raster, given the coordinates provided in columns 1 and 2 in the database? Unfortunately, rasterize does not do the job

ColorRaster= rasterize(c(Database$Xcols, Database$Ycols), BaseRaster, Database $Cols)
Camilo
  • 201
  • 2
  • 6

1 Answers1

1

Assuming BaseRaster is your raster object and database has the color the following should work:

plot(BaseRaster, col=colorRampPalette(database$color))(255)

for more information refer plot{raster}

Vishal R
  • 1,279
  • 1
  • 21
  • 27
  • Thanks Vishal. I tried your code but I get the following error: "no values associated with this RasterLayer" – Camilo Mar 03 '16 at 06:55
  • If one fill the raster with say a value of 1 (like: BaseRaster[]=1) and then run your code, one get the following error: "Error in col[x] : object of type 'closure' is not subsettable" – Camilo Mar 03 '16 at 07:07
  • that is not how you create a raster Camilo. Try BaseRaster <- as.raster(matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)) More help on raster : https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/as.raster.html – Vishal R Mar 03 '16 at 07:51