1. Plotting Rasters

Rasters are generally plotted using the plot command from the raster library. Like many functions in the raster library, the syntax is relatively straightfoward. For example, consider the following plot of a US population count raster:

library(raster)
us.pop <- raster("RGIS3_Data/us_population_raster.asc")
plot(us.pop)

1.1 Managing Breaks

As you can see, however, the raster seems kind of washed out due to the color scaling – most places have no-one, so the default color ramp results in most places being empty. The easiest fix is to just take logs as follows:

us.pop.logged <- us.pop
values(us.pop.logged) <- log(values(us.pop.logged))
plot(us.pop.logged)

But the more sophisticated solution is to use the classInt library just as we did with vector data:

library(classInt)

# First, we need to drop the 0 values in population. There are SO MANY that
# it confuses classInterval
value.vector <- values(us.pop)
value.vector <- value.vector[value.vector != 0]

breaks.qt <- classIntervals(value.vector, n = 15, style = "quantile", intervalClosure = "right")

plot(us.pop, breaks = breaks.qt$brks)

1.2 Managing Colors

We can also use custom colors as with spplot, though not you don’t have to pass the number of cuts to plot as you did with spplot:

library(RColorBrewer)
my.palette <- brewer.pal(n = 20, name = "OrRd")
plot(us.pop.logged, col = my.palette)

1.3 Managing Extent

Controlling zoom is similar, thought slightly different from with spplot. The raster plot command takes an extent argument rather than xlim and ylim arguments, though the idea is that same. So to trim this picture to the Western US, you could type:

# Make an extent object, that was a vector with four values: xmin, xmax,
# ymin, ymax
new.extent <- extent(c(-125, -100, 20, 50))

plot(us.pop.logged, ext = new.extent)

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.