I am trying to plot a spatial raster using ggplot2
.
require(raster)
require(ggplot2)
Download data, load as a raster using the raster
package. More details about this data product can be found here. Then convert the raster to points so it plays well with ggplot
.
system('wget https://www.dropbox.com/s/7jsdqgc9wjcdznv/NADP_wet_deposition_nh4_0.5x0.5_grid_annual_R1.txt')
layer<- raster("path/to/raster/NADP_wet_deposition_nh4_0.5x0.5_grid_annual_R1.txt") #you need to specify your own path here, wherever the downloaded file is saved.
raster.points <- rasterToPoints(layer)
raster.points <- data.frame(raster.points)
colnames(raster.points) <-c('x','y','layer')
Now use ggplot2
to make a map, and lay over the raster.
mp <- NULL
#grab US map and choose colors
map.US <- borders("usa", colour='white',fill='black', lwd=0.4)
mp <- ggplot(data=raster.points, aes(y=y, x=x))
mp <- mp + map.US
mp <- mp + geom_raster(aes(fill=layer))
mp <- mp + theme(axis.text.y=element_blank(),
axis.text.x=element_blank(),
axis.title.y=element_blank(),
axis.title.x=element_blank(),
axis.ticks=element_blank(),
panel.background = element_rect(fill='black'),
plot.background = element_rect(fill='black'),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank())
mp
The output looks like this:
As you can see, things almost line up, but not quite. everything is shifted slightly to the right. What may be causing this and how can I fix it?