0

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?

bill999
  • 2,147
  • 8
  • 51
  • 103

2 Answers2

1

You can use ggplot2::geom_path(). No need to convert into sf object, just use the coordinates.

Alvaro Morales
  • 1,845
  • 3
  • 12
  • 21
0

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")
Pep
  • 33
  • 6