Change longitude and latitude values of sf objects in r

Viewed 379

I am new to sf. In the following code, I generated two maps, one for USA and one for Australia. I would like to move those two next to each other on the same ggplot. I have tried to change longitude and latitude values for Australia within geometry. I just wonder if there is a quick way to do this. Any suggestions would be appreciated.

library(tidyverse)
library(sf)
library(rnaturalearth)
map_au <-ne_states(country = c("australia"), returnclass ="sf") %>%
  select(state = name, geometry)
map_us <-ne_states(country = c("united states of america"), returnclass ="sf") %>%
  select(state = name, geometry) %>% 
  filter(!state %in% c("Alaska", "Hawaii"))
ggplot(data = map_us, aes(fill = state))+
  geom_sf()+
  geom_sf(data = map_au)+ 
  theme(legend.position = "none")

Created on 2020-11-04 by the reprex package (v0.3.0)

1 Answers

sf allows you to carry out arbitrary affine transformations on geometries, including translation. We can move geometries by just adding a coordinate vector, or using a transformation matrix (unnecessary here). We also need to replace the CRS of the object in order to plot it again.

Please do note that this is effectively moving the shape on a flat plane, which may not be exactly what you want to do. In particular, real areas and distances are not preserved (I do not know if Australia having more degrees latitude from north to south than the continental US represents more metres...)

library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.1, GDAL 3.1.1, PROJ 6.3.1
library(rnaturalearth)
map_au <- ne_states(country = c("australia"), returnclass = "sf") %>%
  select(state = name, geometry)
map_us <- ne_states(country = c("united states of america"), returnclass = "sf") %>%
  select(state = name, geometry) %>%
  filter(!state %in% c("Alaska", "Hawaii"))

map_au_moved <- map_au
st_geometry(map_au_moved) <- st_geometry(map_au_moved) + c(-180, 60)
st_crs(map_au_moved) <- st_crs(map_au)

ggplot(data = map_us, aes(fill = state))+
  geom_sf()+
  geom_sf(data = map_au_moved)+ 
  theme(legend.position = "none")

Created on 2020-11-03 by the reprex package (v0.3.0)

Related