RasterVis R – How to Add Line Shapefile to 3D Raster Plot
linerraster
I have generated a 3D raster plot using the plot3D function in the rasterVis package in R.
For enhanced data visualisation, I want to add a line shapefile, representing a sampling transect, to the 3D plot.
Does anyone know how to do this in R?
Best Answer
Use lines3d from the rgl package but make sure to plot the raster with adjust=FALSE or the axes won't line up.
Where r is a raster and xyz is a data frame with x, y, z (height) locations, I do:
plot3D(r, col = rainbow, adjust=FALSE)
lines3d(xyz)
and get
You can get the heights of points from the raster using extract if you don't have them already, and you might want to add a little offset to the heights to keep them just clear of the terrain, so they don't get clipped by any interpolation. You can see my line gets a bit clipped because it's a rough transect with only ten points.
You can use any rgl package functions to augment that plot, such as axis3d("x") to show the x-axis.
library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))
r <- rast(v)
Solution:
x <- rasterizeGeom(v, r, "length")
plot(x); lines(v)
The below is a solution with the older spatial packages. It is based on Jeffrey Evans' answer, but this one is much faster as it does not use rasterize
library(raster)
library(rgdal)
library(rgeos)
roads <- shapefile("TZA_roads.shp")
roads <- spTransform(roads, CRS("+proj=utm +zone=37 +south +datum=WGS84"))
rs <- raster(extent(roads), crs=projection(roads))
rs[] <- 1:ncell(rs)
# Intersect lines with raster "polygons" and add length to new lines segments
rsp <- rasterToPolygons(rs)
rp <- intersect(roads, rsp)
rp$length <- gLength(rp, byid=TRUE) / 1000
x <- tapply(rp$length, rp$layer, sum)
r <- raster(rs)
r[as.integer(names(x))] <- x
Best Answer
Use
lines3d
from thergl
package but make sure to plot the raster withadjust=FALSE
or the axes won't line up.Where
r
is a raster andxyz
is a data frame with x, y, z (height) locations, I do:and get
You can get the heights of points from the raster using
extract
if you don't have them already, and you might want to add a little offset to the heights to keep them just clear of the terrain, so they don't get clipped by any interpolation. You can see my line gets a bit clipped because it's a rough transect with only ten points.You can use any
rgl
package functions to augment that plot, such asaxis3d("x")
to show the x-axis.