Dominik - 3 years ago 246
R Question

# plot raster with discrete colors using rasterVis

I have a few rasters I would like to plot using gplot in the rasterVis package. I just discovered gplot (which is fantastic and so much faster than doing data.frame(rasterToPoints(r))). However, I can't get a discrete image to show. Normally if r is a raster, I'd do:

``````rdf=data.frame(rasterToPoints(r))
rdf\$cuts=cut(rdf\$value,breaks=seq(0,max(rdf\$value),length.out=5))
ggplot(rdf)+geom_raster(aes(x,y,fill=cuts))
``````

But is there a way to avoid the call to rasterToPoints? It is very slow with large rasters. I did find I could do:

``````cuts=cut_interval(r@data@values,n=5)
``````

but if you set the fill to cuts it plots the integer representation of the factors.

Here is some reproducible data:

``````x=seq(-107,-106,.1)
y=seq(33,34,.1)
coords=expand.grid(x,y)
rdf=data.frame(coords,depth=runif(nrow(coords),0,2)))
names(rdf)=c('x','y','value')
r=rasterFromXYZ(rdf)
``````

Thanks

`gplot` is a very simple wrapper around `ggplot` so don't expect too much from it. Instead, you can use part of its code to build your own solution. The main point here is to use `sampleRegular` to reduce the number of points to be displayed.

``````library(raster)
library(ggplot2)

x <- sampleRegular(r, size=5000, asRaster = TRUE)
dat <- as.data.frame(r, xy=TRUE)
dat\$cuts <- cut(dat\$value,
breaks=seq(0, max(dat\$value), length.out=5))
ggplot(aes(x = x, y = y), data = dat) +
geom_raster(aes(x, y, fill=cuts))
``````

However, if you are open to plot without `ggplot2` you may find useful this other answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download