I am trying to create a script that will generate a 2d topographic or contour map for a given set of coordinates. My goal is something similar to what is produced by
contour(volcano)
but for any location set by the user. This has proved surprisingly challenging! I have tried:
library(elevatr)
library(tidyr)
# Generate a data frame of lat/long coordinates.
ex.df <- data.frame(x=seq(from=-73, to=-71, length.out=10),
y=seq(from=41, to=45, length.out=10))
# Specify projection.
prj_dd <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
# Use elevatr package to get elevation data for each point.
df.sp <- get_elev_point(ex.df, prj = prj_dd, src = "epqs")
# Convert from spatial to regular data frame, remove extra column.
# Use tidyr to convert to lat x lon table with elevation as fill.
# Sorry for the terrible code, I know this is sloppy.
df <- as.data.frame(df.sp)
df$elev_units <- NULL
df.w <- df %>% spread(y, elevation)
df.w <- as.matrix(df.w)
This creates a matrix similar to the volcano
dataset but filled with NA
s except for the 10 lat/lon pairs with elevation data. contour
can handle NA
s, but the result of contour(df.w)
has only a single tiny line on it. I'm not sure where to go from here. Do I simply need more points? Thanks in advance for any help--I'm pretty new to R and I think I've bitten off more than I can chew with this project.
Sorry for delay in responding. I suppose I need to check SO for
elevatr
questions!I would use
elevatr::get_elev_raster()
, which returns a raster object which can be plotted directly withraster::contour()
.Code example below grabs a smaller area and at a pretty coarse resolution. Resultant contour looks decent though.
If it is a requirement to use
graphic::contour()
, you'll need to convert the raster object to a matrix first withraster::as.matrix(elev)
. That flips the coords though and I haven't spent enough time to try and get that part figured out... Hopefully theraster
solution works for you.