Plotting Raster object with points at exact position - r

I have a raster object to which I would like to add points.
However, when I change plot size, by making it full screen for example, the points change their positions.
Is there a way to give them exact positions, independent of plot size?
reproducable code:
r<- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
plot(r)
points(x=-50,y=20)
points(x=-50,y=-90)
I'm not allowed to post images. But the lower point gets out of the coloured region when I make the device smaller or moves more into the coloured region when I make the device bigger.
Cheers

this problem has been exposed here too: plotting spatial points over a raster layer in r.
I tried to overpass it by creating a SpatialPointsDataFrame:
r<- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
plot(r)
points(x=-50,y=20)
points(x=-50,y=-90)
coor1<- data.frame(Lat=-50,Lon=20)
point1 <- SpatialPointsDataFrame(
data.frame(coor1$Lon,coor1$Lat),
data.frame('Landriano')
)
x11()
plot(r)
plot(point1, add=T)
The only solution I see is once you overlap the point over the raster you shouldn't change the plot window size. Otherwise the points will be shifted somewhere randomly...

Related

R raster::crop() The upper boundary of my cropped raster is always horizontal- why?

I'm trying to crop a large multipolygon shapefile by a single, smaller polygon. It works using st_intersection, however this takes a very long time, so I'm instead trying to convert the multipolygon to a raster, and crop that raster by the smaller polygon.
## packages - sorry if I've missed any!
library(raster)
library(rgdal)
library(fasterize)
library(sf)
## load files
shp1 <- st_read("pathtoshp", crs = 27700) # a large multipolygon shapefile to crop
### image below created using ggplot- ignore the black boundaries!
shp2 <- st_read("pathtoshp", crs = 27700) # a single, smaller polygon shapefile, to crop shp1 by
plot(shp2)
## convert to raster (faster than st_intersection)
projection1 <- CRS('+init=EPSG:27700')
rst_template <- raster(ncols = 1000, nrows = 1000,
crs = projection1,
ext = extent(shp1))
rst_shp1 <- fasterize(shp1, rst_template)
plot(rst_shp1)
rst_shp2 <- crop(rst_shp1, shp2)
plot(rst_shp2)
When I plot shp2, the upper boundary is flat, rather than fitting the true boundary of the shp2 polygon.
Any help would be greatly appreciated!
Maybe try raster::mask() instead of crop(). crop() uses the second argument as an extent with which to crop a raster; i.e. it's taking the bounding box (extent) of your second argument and cropping that entire rectangle from your raster.
Something important to understand about raster objects is that they are all rectangular. The white space you see surrounding your shape are just NA values.
raster::mask() will take your original raster, and a spatial object (raster, sf, etc.) and replace all values in your raster which don't overlap with your spatial object to NA (by default, you can supply other replacement values). Though I will say, mask() will likely also take awhile to run, so you may be better off just sticking with sf objects.
I would suggest moving to the "terra" package (faster and easier to use than "raster").
Here is an example.
library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
v <- vect(system.file("ex/lux.shp", package="terra"))[4]
x <- crop(r, v)
plot(x); lines(v)
As edixon1 points out, a raster is always rectangular. If you want to set cells outside of the polygon to NA, you can do
x <- crop(r, v, mask=TRUE)
plot(x); lines(v)
In this example it makes no sense, but you could first rasterize
x <- crop(r, v)
y <- rasterize(v, x)
m <- mask(x, y)
plot(m); lines(v)
I am not sure if this answers your question. But if it does not, then please edit your question to make it reproducible, for example using the example data above.

how to create an extent which is not parallel to X and Y axis R raster

I have below code which creates an extent that is parallel to X and Y axis.
Is there a way to create an extent which is not straight - for example I would like to create 2 lines that are parallel to to one diagonal. But one line is below that diagonal by 10 pixels and the other line is above the diagonal by 10 pixels. Create 2 more lines in similar manner but around the other diagonal and use those 4 lines as edges of my extent
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
png("aaa.png",width=20,height=20)
par(mai=c(0,0,0,0))
image(crop(x,extent(c(0,30,0,30))))
dev.off()
An extent is by definition rectangular (at least in the raster package). But you can define a polygon and use that to crop & mask your raster data.
library(raster)
r <- brick(system.file("external/rlogo.grd", package="raster"))
plotRGB(r)
p <- spPolygons(rbind(c(20, 20), c(30, 50), c(70, 50), c(60, 20)))
plot(p, add=TRUE, lwd=4, border='red')
x <- crop(r, p)
m <- mask(x, p)
plotRGB(m)
plot(p, add=TRUE, lwd=4, border='red')
I suggest trying select() with use="pol" parameter. This will allow for an interactive selection of a region on a plot, although the resulting region might not be as precise as you want it.
Edit with a code:
Here is how I would go about it:
x1 <- select(x, use = "pol")
This will open x as an image in a new window (in Plots tab if you use RStudio). Now you can use your mouse to select a region: just click on points which surround the region you want to have. After you are done clicking hit Esc and the new image will be saved as x1 object. You can print/save it then.

How to properly project and plot raster in R

I have a raster in an equal area Behrmann projection and I would like to project it to the Mollweide projection and plot.
When I do this with the following code, however, the plotting doesn't seem right, as the map extends to the sides, and there are outlines of various landmasses where I wouldn't expect them.Also, the map extends beyond the plot window.
Can anyone please help me get this to plot nicely?
Thanks!
The data file used can be downloaded from this link.
Here is the code I have so far:
require(rgdal)
require(maptools)
require(raster)
data(wrld_simpl)
mollCRS <- CRS('+proj=moll')
behrmannCRS <- CRS('+proj=cea +lat_ts=30')
sst <- raster("~/Dropbox/Public/sst.tif", crs=behrmannCRS)
sst_moll <- projectRaster(sst, crs=mollCRS)
wrld <- spTransform(wrld_simpl, mollCRS)
plot(sst_moll)
plot(wrld, add=TRUE)
Alright, since the example at this page seems to work, I tried to mimic it as much as possible. I think problems arise because the far left and far right side of the raster image overlap. Cropping and an intermediate reprojection to Lat-Lon as in the example seem to solve your problem.
Perhaps this workaround can be a basis for a more elegant solution that directly addresses the problem, as it is not benificial to reproject a raster twice.
# packages
library(rgdal)
library(maptools)
library(raster)
# define projections
mollCRS <- CRS('+proj=moll')
behrmannCRS <- CRS('+proj=cea +lat_ts=30')
# read data
data(wrld_simpl)
sst <- raster("~/Downloads/sst.tif", crs=behrmannCRS)
# crop sst to extent of world to avoid overlap on the seam
world_ext = projectExtent(wrld_simpl, crs = behrmannCRS)
sst_crop = crop(x = sst, y=world_ext, snap='in')
# convert sst to longlat (similar to test file)
# somehow this gets rid of the unwanted pixels outside the ellipse
sst_longlat = projectRaster(sst_crop, crs = ('+proj=longlat'))
# then convert to mollweide
sst_moll <- projectRaster(sst_longlat, crs=mollCRS, over=T)
wrld <- spTransform(wrld_simpl, mollCRS)
# plot results
plot(sst_moll)
plot(wrld, add=TRUE)

Merging 2 raster images into one plot using the `raster` package

I would like to add an enlarged portion of my map to the original map and have as the final product, one map that shows both the original map, and also the enlarged/zoomed portion. Using the meuse dataset as an example:
library(sp)
library(lattice)
data(meuse)
coordinates(meuse)=~x+y
gridded(meuse)<-TRUE
rasters.m<-list()
for (i in 1:12){
rasDF <- raster(meuse, layer=i)
rasters.m[[i]]<-rasDF
}
stack.sp<-stack(rasters.m)
plot(stack.sp) # gives a gridded view of the stacked rasters. But now I would like to zoom in..
zoom.ent<-zoom(stack.sp,1) # The zoomed in portion appears as a new window, with the boundaries of the zoomed area highlighted in red on the original map.
I am not sure if there is a command in the raster or rasterVIS packages that would allow one to add the zoomed in part of the raster onto the original map. I have tried the par function but that doesn't work. Any suggestions would be welcomed.
This is more or less the same question you asked here. For Raster* objects you have to use the shift function. The result can be combined with the +.trellis function of the latticeExtra package:
library(raster)
library(rasterVis)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
rZoom <- crop(r, extent(180000, 181000, 330000, 331500))
displaced <- shift(rZoom, x = -1200, y = 2000)
levelplot(r) + levelplot(displaced)

An irregular polygon area as plot on spatstat

it's my first time using the spatstat package, so I would like some advice. I am attempting to plot coordinate data into a irregular polygon area (format .shp), to calculate spatial analysis like Ripley's K. How can I add an irregular polygon area as a plot? How can I merge the .ppp data from the coordinates into the polygon area?
I have used the following codes:
Converting the coordinate data to .ppp format
library(spatstat)
library(sp)
library(maptools)
tree.simu <- read.table("simulation.txt", h=T)
tree.simu.ppp <-ppp(x=tree.simu$X,y=tree.simu$Y,window=owin(c(min(tree.simu$X),max(tree.simu$X)),c(min(tree.simu$Y),max(tree.simu$Y))))
plot(tree.simu.ppp)
With this function I am considering the plot area as the max and min valeu of the coordinates. I would like to put the polygon boundary as the plot.
Ploting the irregular polygon area
area <- readShapePoly("Area/Fragment.shp")
plot(area)
plot(tree.simu.ppp, add=T)
or
points(tree.simu.ppp)
The package accept the last function but, when I try to plot both files together, seems like that the .shp file it is fill the whole area. I can't visualize the coordinates data.
Thank you, I really appreciate your help!
ps.: If you know any material with those question, please I would be happy to take a look
This is indeed due to inconsistent bounding boxes as conjectured in the comment by #jlhoward. Your points are in [273663.9, 275091.45] x [7718635, 7719267] while the polygon is contained in [-41.17483, -41.15588] x [-20.619647, -20.610134].
Assuming the coordinates were indeed consistent with the window the correct way way of getting it into a ppp object would be:
library(spatstat)
library(sp)
library(maptools)
area <- readShapePoly("Area/Fragment.shp")
area <- as(area, "owin")
tree.simu <- read.table("simulation.txt", h=T)
tree.simu.ppp <-ppp(x=tree.simu$X,y=tree.simu$Y,window=area)
However, you will get a warning about your points being rejected since they are outside the window, and the object will contain no points.

Resources