0

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.

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.