Skip to content

Instantly share code, notes, and snippets.

@seasmith
Last active May 30, 2017 16:52
Show Gist options
  • Save seasmith/9688fd83d0a86073652c47fb3f6d3c4a to your computer and use it in GitHub Desktop.
Save seasmith/9688fd83d0a86073652c47fb3f6d3c4a to your computer and use it in GitHub Desktop.
From base to ggplot2: Converting the NC affine transformation example from sf vignette #3
# The following is a "conversion" from base to ggplot2
# of the affine transformation from the sf package's
# third vignette:
# https://cran.r-project.org/web/packages/sf/vignettes/sf3.html#affine-transformations
library(sf)
library(magrittr)
nc <- st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)
cntrd <- nc %>%
st_geometry() %>% # not needed
st_centroid
rot <- function(a) matrix(c(cos(a), sin(a), -sin(a), cos(a)), 2, 2)
ncg2 <- (nc %>% st_geometry() - cntrd) * rot(pi / 2) * 0.75 + cntrd
# ggplot2::geom_sf() only plays with objects of class sf.
# Therefore, two more sf objects are needed in order to
# assign the above class sfc objects into.
## ----
# UPDATE: not necessary. Can supply class sfc objects
# directly to data argument in geom_sf().
# See: https://github.com/tidyverse/ggplot2/issues/2073
## ----
nc2 <- nc
nc3 <- nc
st_geometry(nc2) <- ncg2
st_geometry(nc3) <- cntrd
# ALSO: nc2 is now missing its epsg and proj4string.
# This must be assigned before plotting.
st_crs(nc2) <- st_crs(nc3)
# Now we may plot.
library(ggplot2) # devtools::install_github("tidyverse/ggplot2")
library(ggthemes)
nc %>%
ggplot() +
geom_sf(color = "gray", fill = "white") +
geom_sf(data = nc2, color = "black", fill = "white") +
geom_sf(data = nc3, color = "red", shape = 1, size = 0.25) +
theme_map()
# The only problem with this "conversion" is that
# the red circles are now very squiggly circles.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment