Add curves to raster map? - r

would it be possible to add isoclines or something like "filled.contour" to a raster map?
E.g. to a Bioclim variable? (RasterLayer)
# Download Bioclim data
library(dismo)
tmin_06<-getData("worldclim", var="tmin", res=0.5, lon=10, lat=70)
# plot tmin
plot(tmin$tmin1_06)
And then add e.g. filled.contour {graphics}
I can’t seem to extract the correct values from the RasterLayer and get an error massage:
"cannot coerce type 'S4' to vector of type 'double'"
Or what would you use to illustrate the direction of change in a map like this for temperature, or for equidistance in an elevation map?
Thank you!
Daniel

Here are two approaches:
# example data
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
plot(r)
contour(r, add=TRUE)
# or
filledContour(r)

Related

Overlay shapefile over Raster in Multiple plots

I am trying overlay the shapefile of south asia on top of multiple raster plots using the code as below: 'a' is a multilayered raster file. Here is the link to the data (917KB size) Test_Data
ras <- list.files("/filepath/", pattern = "\\.tif$", full=TRUE)
s <- stack(ras)
south_asia <- readOGR('/filepath/south_asia.shp') #to import shapefile
cropped <- crop(x = s, y = extent(south_asia)) #crop raster
plot(cropped)
plot(south_asia, add=TRUE)
This code gives me one shapefile and multiple raster plots. How do i overlay the shapefile on top of the rasters?
Any help will be appreciated.
P.S: They are in same CRS
Thanks
First, please try to give a reproducible example instead of a link to download files externally!
If you manually construct the plot (e.g. using par with base plotting) you can get your desired behaviour:
library(raster)
## testdata
# shapefile
shp <- getData(country='IND', level=1)
# raster
r <- getData('alt', country='IND', mask=TRUE)
# create 4 layer rasterstack
rs <- stack(r,r,r,r)
## finally plot
# 2 rows, 2 cols
par(mfrow=c(2,2))
# loop layers
for (ii in 1:nlayers(rs)){
plot(subset(rs,ii), main=names(rs)[ii])
plot(shp, add=T)
}
Edit:
Use plot(subset(rs,ii), main=names(rs)[ii]) in the loop to plot the respective layer.
The result:
I would suggest using the argument addfun in the plot option for raster stack/brick
For example:
# Function to add shapefile "shp_file" on each raster plot
add_shp=function(){plot(shp_file, bg="transparent", add=TRUE)}
#Plot selected raster of a raster stack, rs
plot(rs[[c(1:5)]],col=tim.colors(5),addfun=add_shp)
This will add shapefile shp_file to each of the 5 plots from the rasterstack rs.

How to create moving window filter of semivariogram outputs in R using focal area function?

I'm trying to create a raster filled with semivariogram outputs such as the sill and range of an area which describes the spatial autocorrelation. I wanted to try using the focal function in R as a way to scan an area, and the variogram function from gstat package to calculate sill and range.
I've tried the following code, but there are issues with the function.
library(raster)
library(gstat)
r <- raster()
r[] <- 1:ncell(r)
ra <- aggregate(r, 5)
plot(ra)
v<-variogram(layer~1,as(ra,"SpatialPixelsDataFrame"))
plot(v)
f = fit.variogram(v, vgm("Sph"))
f$psill[2]
f$range
var.sill<-function(x){
names(x)<-c("layer")
v<-variogram(layer~1,as(x,"SpatialPixelsDataFrame"))
f = fit.variogram(v, vgm("Sph"))
f$psill[2]
}
var.sill(ra)
# 374758092
## in a window surrounding each focal cell
rpsill <- focal(ra, w=matrix(1/225, ncol=15, nrow=15), fun=var.sill)
plot(rpsill)
The error states," Error in as(x, "SpatialPixelsDataFrame") :
no method or default for coercing “numeric” to “SpatialPixelsDataFrame” "
I would appreciate any help with this or if there is another way to potential create these new rasters please let me know too.
Thank you.

Plotting 3D Raster (DEM) in R?

I am trying to plot a 3D surface of a DEM imported as a raster in R using the raster package.
So far, my code is:
DEM <- raster("DSM_TLS_2010_25cm_v4.tif")
DEM <- setMinMax(DEM)
col <- rainbow(20)
plot(DEM, col=col, zlim=c(0,790.22), main="Digital Elevation Model (DEM)")
Which works perfect for a 2D plot of the DEM, but, when I try to make it 3D, with:
plot3d(DEM)
or
surface3d(DEM)
It says cannot coerce type 'S4' to vector of type 'double'.
I am sure that answer is very simple but I have not managed to get it working with the similar questions that I have found.
The raster() function returns RasterLayer objects, and I suspect that the plot3d() and surface3d() functions in the rgl package do not (or do not fully) support RasterLayer objects.
The plot3D() function in the RasterVis package, however, does. Give this a try:
install.packages("rasterVis")
library(rasterVis)
plot3D(DEM) # note: 3D not 3d

Spatial interpolation (Kriging), polygon instead of raster output

Is there a (easy) way to convert a SpatialPixelsDataFrame (from krige) to e.g. a SpatialPolygonsDataFrame (vectorgraphic instead of pixelgraphic).
It would be fine to set value ranges and interpolate the raster to a polygon or use another krige method that generates a SpatialPolygonsDataFrame. I'm looking forward to a simple example.
krige example: i.e. in the book https://oscarperpinan.github.io/spacetime-vis/ 8.1.5 Spatial Interpolation, complete source https://github.com/oscarperpinan/spacetime-vis/blob/master/bubble.R
library(gstat)
airGrid <- spsample(NO2sp, type="regular", n=1e5)
gridded(airGrid) <- TRUE
airKrige <- krige(mean ~ 1, NO2sp, airGrid)
spplot(airKrige["var1.pred"],
col.regions=colorRampPalette(airPal)) + ...
Something like this might work:
library(raster)
x <- raster(airKrige["var1.pred"])
y <- cut(x, c(10,20,30,40,50,60,70))
z <- rasterToPolygons(y, dissolve=TRUE)
spplot(z)

Is it possible to overlay SpatialLinesDataFrame and SpatialPolygonDataFrame

I am wondering if this is possible to do this R .
I have one data as SpatialLinesDataFrame and another as spatialPolygonDataFrame. Is it possible to overlay these two data ?
When I try to overlay these I get the following error:
jd <- overlay(res,hello)
Error in function (classes, fdef, mtable) : unable to find an inherited method for function
‘overlay’ for signature ‘"SpatialLinesDataFrame", "SpatialPolygonsDataFrame"’
In the above code res is the SpatialLinesDataFrame and hello is SpatialPolygonDataFrame.
I have an shapefile and then I have data points with x,yand z
coordinates. I want to show the contour lines on the shapefile.
The procedure I used is using akima package to do the interpolation. The
code I used to interpolate is
fld <- interp(x,y,z)
Then I changed this to spatial object by using following code:
res <-ContourLines2SLDF(contourLines(fld))
The above command would store the contourlines as spatial data.
Then I read the shapefile and I plot both shapefile and res as follows:
p1 <-
spplot(hello,sp.layout=list(list("sp.lines",res)),col="blue",lwd=0,fill="grey",colorkey=F)
p1
"hello" is my shapefile and "res" is the object I created as shown above.
The problem is contour stored in "res" extends beyond the shapefile. So I
want to clip that contour with the shapefile and only display the contour
within the shapefile area.
So I am looking for a way to clip the contour layer with the polygon layer.
I have attached the image I got with my code.
In the image you can see the lines out of the shapefile. I also want to know
how can I display the contour levels on the map.
Thank you so much.
Jdbaba
I also want to know what does overlay does exactly. Does it intersect the area of both the data ?
Thank you.
It sounds like you're trying to clip your lines to the polygon extent. Use gIntersection from the rgeos package. Here's a reproducible example:
library(rgeos)
xx <- SpatialPoints(coords=matrix(data=c(0,0), nrow=1))
xx <- gBuffer(spgeom=xx, width=1)
yy <- SpatialLines(list(Lines(Line(matrix(c(-1,1,-1,1), nrow=2)), ID=1)))
zz <- gIntersection(yy, xx)
You can overlay the plot like so:
plot(xx)
plot(zz, add = TRUE, col = "blue")
Noah's answer has worked quite well for me. However, the output of his answer is a SpatialLines object, which cannot be saved as a shape file.
My two cents here is about how you can convert your SpatialLines object into a SpatialLinesDataFrame and save it as a shape file.
res.df <- fortify(res) # create data frame of res, your original SpatialLinesDataFrame
data <- data.frame(id = unique(res.df$id)) # get ids of road segments
rownames(data) <- data$id
# transform SpatialLines object into SpatialLinesDataFrame
zzSpatialLineDF <- SpatialLinesDataFrame(zz, data) # convert zz object keeping road ids
# 5 Save Shape File to your working directory
writeOGR(zzSpatialLineDF, dsn = '.', layer ='zzSpatialLineDF', driver = 'ESRI Shapefile')

Resources