Skip to content

Instantly share code, notes, and snippets.

@ldemaz
Created March 22, 2019 10:59
Show Gist options
  • Save ldemaz/7aa89dbbf1d60c4fbd8bbe404c4f7d77 to your computer and use it in GitHub Desktop.
Save ldemaz/7aa89dbbf1d60c4fbd8bbe404c4f7d77 to your computer and use it in GitHub Desktop.
Converting plot to lat-long coordinates
library(tidyverse)
library(sf)
library(raster)
# set up dummy dataset
# start with raster having 0, 0 origin
r <- raster(extent(0, 1, 0, 1), res = 0.02)
set.seed(1)
r[sample(1:ncell(r), 10)] <- 1:10
plot(r, xaxs = "r")
# collect 0, 0 origin coordinates and "tree" ids from dummy raster
tree_mat <- Which(r, cells = TRUE, na.rm = TRUE) %>%
cbind(xyFromCell(r, .), id = .) %>% data.frame %>% as_tibble %>%
mutate(id = factor(id))
# rescale plot coordinates to lat, long range, e.g.
bb <- c(37.0055, 37.0056, -18.1356, -18.1355) # xmin, xmax, ymin, ymax
# rescale x and then y, wrapping plot coordinates with a 0 and max value
# (1 in this example) to preserve distances from extremes
treelon <- scales::rescale(c(0, tree_mat$x, 1), to = bb[1:2])
treelat <- scales::rescale(c(0, tree_mat$y, 1), to = bb[3:4])
# add recaled coordinates to tibble, dropping extremes added on
tree_mat <- tree_mat %>%
mutate(lon = treelon[-c(1, length(treelon))],
lat = treelat[-c(1, length(treelat))])
# side-by-side plot for comparison
p1 <- ggplot(tree_mat) + geom_point(aes(x, y, color = id))
p2 <- ggplot(tree_mat) + geom_point(aes(lon, lat, color = id))
cowplot::plot_grid(p1 + theme(legend.position = "none"),
p2 + theme(legend.position = "none"),
cowplot::get_legend(p1), nrow = 1, rel_widths = c(1, 1, 0.2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment