Reputation: 543
I have a raster image that I would like to plot with a world map overlay in R. I am able to plot both the raster image and map overlay, but the x and y limits specified for the raster plot are not what I specified, leaving an overhang outside of the raster bounds that I do not want displayed on my map.
Here is my code:
library(raster)
library(rworldmap)
r <- raster(ncol=500, nrow=500)
values(r) <- 1:ncell(r)
plot(r, ylim=c(-50,50), xlim=c(-100,100), col=rev(pal(100)))
world <- getMap(resolution="high")
map(world, add=TRUE, lwd=0.5)
Which produces this map:
Any ideas for how to get rid of the white non-raster overhangs running along the top and bottom of the figure? Thanks!!!
Upvotes: 0
Views: 660
Reputation: 1140
The following example is a slight modification of your code.
library(raster)
library(rworldmap)
library(rgeos)
r <- raster(ncol=500, nrow=500)
values(r) <- 1:ncell(r)
r <- crop(r, extent(-100, 100, -50, 50))
world <- getMap(resolution="high")
world <- gBuffer(world, byid = T, width = 0)
world <- crop(world, r)
png(file = "C:/Example_Plot.png", height = 500, width = 880)
plot(r)
plot(world, add = T, lwd = 0.5)
dev.off()
The strategy is essentially to crop the polygons to the extent of the raster object and to specify the width and height of the output file.
Upvotes: 1