I am trying to plot a raster image using Leaflet, however I am having issues getting the colours right.

I've read in the raster like this and plot the the resulting raster variable.


But when I try to plot the raster using leaflet and the addRasterImage() function there are two things I notice. Firstly, it looks as its it is doing some kind of antialising between the colours. Secondly, it is putting some colours in that shouldn't be there.

pal<-colorNumeric(ras@legend@colortable,0:255,na.color = "transparent")
leaflet() %>% addRasterImage(ras,colors = pal)  

This is the raster produced using plot(): enter image description here An this is the one produced using leaflet: enter image description here

The questions are:

  1. Is it possible to disable the antialising-like behaviour?
  2. Why is it changing colours of some squares?

I'm also not entirely sure whether I am creating the pallete in the right way. Any tips on these questions?

1 Answer 1


It seems that leaflet is reprojecting the raster and that is causing some interpolation of cells.

Since your grid is a lat-long decimal degree grid, if you add project=FALSE you can get it to skip this step and the output has none of these interpolated pixels and all seems to be the right colour:

leaflet() %>% addRasterImage(ras,colors = pal) 

enter image description here


leaflet() %>% addRasterImage(ras,colors = pal, project=FALSE)  

enter image description here


If you have categorical data that isnt on a lat-long grid and you need to reproject it then you should use method="ngb" to select the nearest neighbour cell for reprojection otherwise values get interpolated between integers which are no longer valid categories (unless you round them first...).

  • Ah perfect thank you! Commented Feb 22, 2021 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.