Plot filled areas for sea/ocean and land mass based on {osmdata} using {ggplot2}

Viewed 45

The reprex below shows how I would like to create a map via {osmdata} and {ggplot2} that has sea/ocean in it. I want to color-fill the land and/or sea area. However, it seems unexpectedly difficult to do so. This blog post even claims that it cannot be done.

This vignette of {osmplotr} seems to have to the solution: "Because OpenStreetMap represents coastline as line objects, all coastline data is contained within the $osm_lines object. The osm_line2poly() function can then convert these lines to polygons which can be used to plot filled areas.". Yet, just as in this similar StackOverflow question, the function throws an error as can be seen at the bottom of the reprex. I also found here that the {tigris} package can provide the necessary polygon data - but only for the US.

So how can I get this to work?

library(osmdata)
library(osmplotr)
library(sf)
library(tidyverse)

# define example bbox
bb <- tribble(
  ~xy,  ~min,  ~max,
  "x", 12.00, 12.18,
  "y", 54.08, 54.20
) %>% column_to_rownames("xy") %>% as.matrix()

# get "water"
water <- opq(bb) %>%
  add_osm_feature(key = "natural", value = "water") %>%
  osmdata_sf()

# get "coastline"
coast <- opq(bb) %>%
  add_osm_feature(key = "natural", value = "coastline") %>%
  osmdata_sf()

# ggplot
ggplot() +
  geom_sf(
    data = water$osm_multipolygons,
    fill = "navy",
    color = NA
  ) + 
  geom_sf(
    data = coast$osm_lines,
    fill = "navy",
    color = "blue"
  )

# trying osm_line2poly()
osmplotr::osm_line2poly(coast$osm_lines, bb)
#> Error in FUN(X[[i]], ...): unbenutztes Argument (V = c(3, 1, 6, 7, 2, NA, 5))

Created on 2022-09-23 with reprex v2.0.2

0 Answers
Related