Home > Back-end >  How to color the area which belongs to some town with `osmdata` and `sf` in R?
How to color the area which belongs to some town with `osmdata` and `sf` in R?

Time:10-25

I've been so frustrated with this for several hours and I can't find a way to do this supposedly simple task. Let's say that we want to color the area of some town/village taken from OpenStreetMap. Here is an example:

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

bb <- getbb("Wetwang", featuretype = "settlement", format_out = "polygon")

town_boundaries <- getbb("Wetwang", featuretype = "settlement") %>% 
  opq() %>% 
  add_osm_feature(key = "boundary", value = "administrative") %>% 
  osmdata_sf() %>% 
  trim_osmdata(bb)

ggplot(town_boundaries$osm_lines)  
  geom_sf()

This produces the following plot:

enter image description here

However, what to do if I want to color the area of this UK village in red? This doesn't work:

ggplot(town_boundaries$osm_lines)  
  geom_sf(fill = "red")

So, what should I do?

CodePudding user response:

Maybe plotting the polygon rather than the boundary allows use of fill...

library(osmdata)
library(tidyverse)

bb <- getbb("Wetwang", featuretype = "settlement", format_out = "polygon")

town_boundaries <- getbb("Wetwang", featuretype = "settlement") %>% 
  opq() %>% 
  add_osm_feature(key = "boundary", value = "administrative") %>% 
  osmdata_sf() %>% 
  trim_osmdata(bb)


ggplot(town_boundaries$osm_multipolygons)  
  geom_sf(fill = "red")

Created on 2022-10-24 with reprex v2.0.2

  • Related