Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to color the area which belongs to some town with `osmdata` and `sf` in R?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading