[R] Recommended ways to draw US Census map on Open Street Map base map?

Kevin Zembower kev|n @end|ng |rom zembower@org
Tue Jun 6 20:37:45 CEST 2023


Hello, all,

I asked a version of this question on the R-sig-geo list, but didn't get 
any response. I'm asking here in the hopes of a wider audience.

I'm trying to draw US Census map data, fetched with tigris, on top of a 
base map fetched by the package OpenStreetMap. I'm hoping for the most 
straight-forward solution. I made significant progress with leaflet(), 
but didn't need the interactivity of the map. I just need a 2D, static 
map that I can print and include in a document.

Here's some of what I've tried so far:
==========================================
library(tidyverse)
library(tigris)
options(tigris_use_cache = TRUE)
library(OpenStreetMap)
library(ggplot2)

## Get an Open Street Map:
rw_map <- openmap(nw, se,
                   type = "osm",
                   mergeTiles = TRUE) %>%
     openproj(projection = "+proj=longlat +ellps=WGS84 +datum=WGS84 
+no_defs")

## Get an example census map:
rw_tract <- tracts(state = "MD",
                     county = "Baltimore city",
                     year = "2020") %>%
     filter(NAME == "2711.01")

## This works:
autoplot.OpenStreetMap(rw_map)

## So does this:
plot(rw_tract$geometry)

## These don't:
autoplot.OpenStreetMap(rw_map) +
     geom_sf(rw_tract$geometry)

ggplot(map_data(rw_map), aes(long, lat))


ggplot(aes(x="long", y="lat")) +
     geom_sf(rw_map$geometry)
=====================================================

I think my problem in part is failing to fully understand the formats of 
the rw_map and rw_tract containers. rw_tract says it's a simple feature 
collection, but rw_map just gives me lists of the data.

Can anyone help nudge me along in getting my rw_tract to be drawn on my 
rw_map? Any advice or guidance on putting together map data from 
different sources?

And an over-arching question: Is moving in this direction, with ggplot2, 
the way you would recommend accomplishing this task? Is there a simpler, 
more straight-forward way of doing this?

Thanks in advance for your help and efforts.

-Kevin



More information about the R-help mailing list