Camilo
Camilo

Reputation: 201

How to transfer specific colors to a raster in r

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)

Upvotes: 3

Views: 273

Answers (1)

Vishal R
Vishal R

Reputation: 1379

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}

Upvotes: 1

Related Questions