Reputation: 307
I'm making a raster data ploting in R, when I adjust to the area I'm working on, R displays the ylim that doesn't want to be cut off.
I tried:
# set lon lat
ylim=c(-4,2)
xlim=c(118,126)
plot(pm10_mean,xlim=xlim, ylim=ylim)
plot(shp, add=TRUE)
plot(shp2, add=TRUE)
but I got picture like this
How to remove free space above 2 and below -4? I just want to plot area in xlim
and ylim
Upvotes: 5
Views: 4016
Reputation: 1
Just as easy to simply plot a NULL plot and add your raster
plot(NULL, xlim = c(-114.5, -35.5), ylim = c(-24.5, 29.5), asp = 30/30,
xlab = "Longitude", ylab = "Latitude")
plot(your_raster, add = T)
Stacking still seems to work
Upvotes: 0
Reputation: 307
I think spplot
works fine but I find it really slow and hard to customize.
I found a more recent duplicate of this question in gis.stackexchange and provided the below answer:
I found that raster::plot
's documentation indicates that you can specify the plotting window and in my experience it has zero effect. Instead it will always assume the extent of the raster you give it.
My suggested workaround is to first draw your desired plot window with a blank object then add the raster plot to this window.
my_window <- extent(-4, 2, 118, 126)
plot(my_window, col=NA)
plot(my_raster, add=T)
For me, this achieves what I'm after. The caveat is if you're plotting a stack or brick, the add functionality doesn't work in my experience. The solution is to use subset
, like plot(subset(my_brick,4), add=T)
Upvotes: 3
Reputation: 1233
I have had this problem before. You can manually resize the plot area to remove the blank areas, or insert polygons to cover the unwanted areas of shapefile. But the safest option is to use spplot
as this will automatically resize the plotting area for you:
require(maptoolS)
require(raster)
data(wrld_simpl)
rs=raster()
rs[]=1
id_shp=wrld_simpl[which(wrld_simpl$ISO2=="ID"),]
rs=crop(rs,id_shp)
rs=disaggregate(rs,40)
rs=mask(rs,id_shp)
spplot(rs,ylim=c(-4,2),xlim=c(118,126),sp.layout=list('sp.lines', id_shp, lwd=2,first=F))
Upvotes: 1