5

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

enter image description here

How to remove free space above 2 and below -4? I just want to plot area in xlim and ylim

ExHunter
  • 307
  • 4
  • 11

3 Answers3

3

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)

brotherJ4mes
  • 159
  • 1
  • 5
  • " you can specify the plotting window and in my experience it has zero effect." is an odd statement as any simple test shows that it works. – Robert Hijmans Dec 03 '20 at 19:49
1

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))

enter image description here

drJones
  • 1,233
  • 1
  • 16
  • 24
  • I want not only land to have a raster value but also the sea – ExHunter Apr 12 '20 at 01:18
  • That was just demonstration as you did not provide a reproducible example. Take the last line of my code and change "rs" to "pm10_mean" and "id_shp" to "shp" to match your data – drJones Apr 12 '20 at 01:30
0

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