5

fiftystater package provides a great map of USA that has Hawaii and Alaska as insets below. The object fifty_states comes already fortified for use with ggplot2. However, I would like to plot this as an sf object using geom_sf.

As a more general question, what is the best way to convert a fortified data.frame back into sf polygon?

library(fiftystater)
fifty_states <– fifty_states

> head(fifty_states)
       long      lat order  hole piece      id     group
1 -85.07007 31.98070     1 FALSE     1 alabama Alabama.1
2 -85.11515 31.90742     2 FALSE     1 alabama Alabama.1
3 -85.13557 31.85488     3 FALSE     1 alabama Alabama.1
4 -85.13156 31.78381     4 FALSE     1 alabama Alabama.1
5 -85.13017 31.77885     5 FALSE     1 alabama Alabama.1
6 -85.11529 31.73157     6 FALSE     1 alabama Alabama.1

note this question polygons from coordinates is kind of similar but doesn't quite do what I need.

sebdalgarno
  • 2,929
  • 12
  • 28

1 Answers1

6

this would work: you first convert to a point sf dataset using st_as_sf, and then create polygons from the points of each state/piece.

sf_fifty <- sf::st_as_sf(fifty_states, coords = c("long", "lat")) %>% 
  group_by(id, piece) %>% 
  summarize(do_union=FALSE) %>%
  st_cast("POLYGON") %>% 
  ungroup()

plot(sf_fifty["id"])

(see also https://github.com/r-spatial/sf/issues/321)

lbusett
  • 5,801
  • 2
  • 24
  • 47
  • 2
    `sfheaders::sf_polygon(x = fifty_states, polygon_id = "id", linestring_id = "piece", x = "long", y = "lat")` will also work. – SymbolixAU Nov 20 '19 at 04:19