ropensci / rnaturalearth

An R package to hold and facilitate interaction with natural earth map data :earth_africa:
http://ropensci.github.io/rnaturalearth/
Other
214 stars 24 forks source link

How to use `ne_states()` with `ggplot()` #51

Closed benyamindsmith closed 1 year ago

benyamindsmith commented 2 years ago

Is it possible to use the data from ne_states() with ggplot2?

From the documentation it seems like its only "out of the box computable" with base R's plot() function.

I'm asking because ne_countries() seems to work pretty well and is pretty easy to read as far as output is concerned because its a tibble is outputted. ne_states() returns a list which is hard to understand exactly what needs to be passed as arguments to work with ggplot.

world_map <- ne_countries(scale = "large", returnclass = 'sf')
europe_map <- world_map %>% filter(continent=="Europe")
ggplot() + 
    geom_sf(data = europe_map) +
    coord_sf(xlim = c(-25, 45), ylim = c(33, 73), expand = FALSE)+
    theme_void()

image

Thanks!

mps9506 commented 2 years ago

You only need to add the return_class argument to specify that the function returns an object of type sf. This should work with any of the natural earth functions:

library(rnaturalearth)
library(ggplot2)

df <- ne_states(country = 'france', returnclass = 'sf')

ggplot(df) +
geom_sf()