Skip to content

Instantly share code, notes, and snippets.

@yutannihilation
Last active June 5, 2018 14:24
Show Gist options
  • Save yutannihilation/f20218f75d891eaadac59f6da54c0310 to your computer and use it in GitHub Desktop.
Save yutannihilation/f20218f75d891eaadac59f6da54c0310 to your computer and use it in GitHub Desktop.
library(ggplot2)
library(tidyverse)
library(patchwork)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

nc_12 <- tibble::rownames_to_column(nc[1:2,], "id")

nc_12_merged <- nc_12 %>%
  st_boundary() %>%
  st_union() %>%
  st_line_merge() %>%
  st_sf()

nc_12_casted <- sf::st_cast(nc_12, "MULTILINESTRING")

p1 <- ggplot(nc_12_casted) +
  geom_sf(colour = "black", fill = "transparent", linetype = "11", size = 4) +
  theme_minimal() +
  ggtitle("casted")

p2 <- ggplot(nc_12_merged) +
  geom_sf(colour = "black", fill = "transparent", linetype = "11", size = 4) +
  theme_minimal() +
  ggtitle("merged")

p1 / p2

Created on 2018-06-05 by the reprex package (v0.2.0).

library(ggplot2)
library(tidyverse)
library(patchwork)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

nc_12 <- nc[1:2,]

nc_12_casted <- sf::st_cast(nc_12, "MULTILINESTRING")

nc_12_merged <- nc_12 %>%
  st_boundary() %>%
  st_union() %>%
  st_line_merge() %>%
  st_sf()

do_plot <- function(x) {
  title <- deparse(substitute(x))
  
  x <- x %>% 
    sf::st_cast("LINESTRING") %>%
    tibble::rownames_to_column("id")
  
  ggplot(x) +
    geom_sf(aes(colour = id), fill = "transparent", linetype = "11", size = 4) +
    gghighlight::gghighlight() +
    theme_minimal() +
    ggtitle(title) +
    facet_wrap(~ id)
}

do_plot(nc_12_merged) / do_plot(nc_12_casted)
#> Warning in st_cast.sf(., "LINESTRING"): repeating attributes for all sub-
#> geometries for which they may not be constant

Created on 2018-06-05 by the reprex package (v0.2.0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment