'How to properly plot sf object

I have data like the following:

enter image description here

These data are obtained from a Stata dataset (.dta exported to .csv) and are intended to plot a map of shapefiles. I import it into R, drop rows with missing data, and convert to sf (I am not sure if this is the best way to do it). I then plot.

coords <- read.csv("filename.csv") %>% drop_na()
coords2 <- st_as_sf(x=coords, coords = c("X_X", "X_Y"))
ggplot(coords2) + geom_sf()

This is what I get:

enter image description here

How can I instead get a map that has lines instead of the points? And how can I shade the individual map areas based on another variable, such as X_ID?



Solution 1:[1]

You might need to use points_to_lines from the sp package.

library(sp)
map <- points_to_line(data = coords, 
                          long = "X_X", 
                          lat = "Y_Y", 
                          id_field = "X_id", 
                          sort_field = "shape_pt_sequence")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pep