Home > other >  Create polygon from coordinates and plot in ggplot
Create polygon from coordinates and plot in ggplot

Time:12-09

I have a series of coordinates that I want to use to create a polygon. Then, I want to add this polygon to a map, but I get an error when using ggplot that I need help fixing.

Example:

# create polygon (probably an easier way to do this, but I think it works)
poly <- st_polygon(list(as.matrix(data.frame(lat = c(40, 40, 60, 60, 40),
                                             lon = c(-60, -40, -40, -60, -60)))))

# plot polygon
plot(poly, border = "red) # plots box with a red outline, so I think it works

ggplot()  
  geom_polygon(data = poly, 
               aes(x = lon, y = lat),
               col = "red") 

Error in `geom_polygon()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (1)
✖ Fix the following mappings: `x` and `y`
Run `rlang::last_error()` to see where the error occurred.

CodePudding user response:

For class sf you need to use geom_sf (although it's technically a spatial polygon).

In your case:

poly |>
    ggplot()  
    geom_sf(aes(geometry = geometry))
  • Related