Week 12
Data Wrangling and Visualization
Week 12 Workshop: Geographic Data
The scripts from class, in order: shapefiles and point data, Census maps, street maps from OpenStreetMap, and terrain. Each section shows a map its script draws: the last one, except for script 4, where it is the fire stations map.
Data. Scripts 1, 2 and 8 read files from your project folder:
Script 1 expects a
bosniafolder holdingged.csvandbosnia.shp(withbosnia.shxandbosnia.dbf). They come from the companion files to Weidmann’s Data Management for Social Scientists: download the zip, then copy itsch11folder into your project and rename itbosnia.Script 2 needs the
dma_exportfolder (dma_export.shpand its companion files), and script 8 needsCrater_Lake.tif(108 MB). Both are on the Course Drive.
Paths. The scripts read and save files in
~/desktop/working/dwv26: put the data there (thebosniaanddma_exportfolders andCrater_Lake.tif), or change thesetwd()andraster()paths to wherever you keep them.The Census. Script 3 needs a Census API key; see Workshop 8, Step 7.
OpenStreetMap. Scripts 4–7 (and the second Crater Lake script) download from OSM’s free Overpass servers, which are often busy and limit how much any one computer can ask for. A query can then sit for minutes and fail with a timeout or an HTTP error such as
502 Bad Gateway,504 Gateway Timeoutor429 Too Many Requests(the last one means you have asked for too much recently). None of these are errors in your code. Wait a few minutes and run the query again, or switch to another server before it:set_overpass_url("https://overpass-api.de/api/interpreter") # the main server set_overpass_url("https://overpass.kumi.systems/api/interpreter") # a mirrorBig areas and broad tags (every road in a city, every
highwayin a park) are the slowest; once a query works, save the result withsaveRDS()so you don’t have to ask again.Packages.
install.packages()any you don’t have:tidyverse,sf,scales,lattice,terra,tmap,RColorBrewer,maptiles,cartogram,ggthemes,tidycensus,osmdata,showtext,ggmap,remotes,rayshader,rasterandmagick. Script 6 usesstr_detect(), so runlibrary(stringr)first if it can’t find it.
1. Bosnia

dwvgis_1_bosnia.R
##Title: DWVGIS 1. Bosnia.R
#Author: Jack Reilly
#Purpose: Illustrate loading a shape file and layering points for the Bosnian civil war
#Requires: ged.csv and bosnia.shp, both in a bosnia folder inside ~/desktop/working/dwv26
library(tidyverse)
library(sf)
#Set the working directory
setwd("~/desktop/working/dwv26")
#Load the event data and inspect it
events <- read.csv("bosnia/ged.csv")
summary(events)
#Declare the spatial element of the event data
events <- st_as_sf(events, coords = c("longitude", "latitude"), crs = 4326)
events
#Begin plotting it
plot(events)
plot(st_geometry(events))
#Load the shape file
bosnia <- st_read("bosnia/bosnia.shp", crs = 4326)
bosnia
#Begin plotting
plot(bosnia)
plot(st_geometry(bosnia), col = "lightgrey")
plot(st_geometry(events), pch = 16, add = T)
plot(st_geometry(events), col = events$best, pch = 16, add = TRUE)
#Let's create a color scale
library(scales)
black_red <- gradient_n_pal(c("black", "red"))
# numeric vector to color
vals <- events$best
rng <- range(vals, na.rm = TRUE) # data domain
z <- rescale(vals, to = c(0, 1), from = rng)
ptcol <- black_red(z) # colors for each point
# plot
plot(st_geometry(bosnia), col = "lightgrey")
plot(st_geometry(events), col = ptcol, pch = 16, add = TRUE)
#This color looks funny
library(lattice)
histogram(events$best)
#Ah. Some large outliers there.
#Let's find the biggest events
events_sorted <- events[order(events$best), ]
tail(events_sorted$best, 10) # 10 lowest
#OK. First, we'll create some groups
events$outlier <- events$best %in% c(3000, 8106)
events$large <- events$best %in% c(144, 150, 197, 270, 300)
#Now, we'll break our point dataset in three: "normal", "large", and "outlier"
large_vals <- c(144, 150, 197, 270, 300)
outlier_vals <- c(3000, 8106)
ev_out <- events[!is.na(events$best) & events$best %in% outlier_vals, ]
ev_large <- events[!is.na(events$best) & events$best %in% large_vals, ]
ev_reg <- events[!is.na(events$best) &
!(events$best %in% c(large_vals, outlier_vals)) &
events$best >= 0 & events$best <= 101, ]
vals <- ev_reg$best
rng <- range(vals, na.rm = TRUE) # data domain
z <- rescale(vals, to = c(0, 1), from = rng)
ptcol <- black_red(z)
plot(st_geometry(bosnia), col = "lightgrey")
plot(st_geometry(ev_reg), col = ptcol, pch = 16, add = TRUE)
#Still dark. what if we made the mean of the color scale the mean of the variable?
mean(ev_reg$best)
median(ev_reg$best)
z <- rescale_mid(vals, to = c(0, 1), from = rng, mid = 7)
ptcol <- black_red(z)
plot(st_geometry(bosnia), col = "lightgrey")
plot(st_geometry(ev_reg), col = ptcol, pch = 16, add = TRUE)
z <- rescale(vals, to = c(0, 1), from = rng)
z <- z ^ 0.7 # lower exponent -> shifts color toward red earlier
ptcol <- black_red(z)
plot(st_geometry(bosnia), col = "lightgrey")
plot(st_geometry(ev_reg), col = ptcol, pch = 16, add = TRUE)
#Still a tough distribution to figure out how to color effectively, even with the larger channels taken out
histogram(ev_reg$best)
#Ok. What about adding the others?
plot(st_geometry(bosnia), col = "lightgrey", main="Bosnian Civil War")
plot(st_geometry(ev_reg), col = ptcol, pch = 16, add = TRUE)
plot(st_geometry(ev_large), col = "maroon", pch = 15, cex=2, add = TRUE)
plot(st_geometry(ev_out[1,]), col = "maroon", pch = 17, cex=3, add = TRUE)
plot(st_geometry(ev_out[2,]), col = "red", pch = 17, cex=3, add = TRUE)
#Legend
legend("bottomleft",
legend = c("Small Event (0–101 casualties)",
"Large Event (102–300)",
"Major Event (3000)",
"Major Event (8106)"),
pch = c(16, 15, 17, 17),
pt.cex = c(0.9, 1.3, 1.8, 2.2),
col = c("red", "#800000", "#800000", "red"),
bty = "o") # <-- draw box
#Join the two datsets together to allow for counting
joined <- st_join(events, bosnia)
eventcounts <- joined |>
as.data.frame() |>
group_by(id.y) |>
count(name = "num_events")
eventcounts2. DMAs

dwvgis_2_dmas.R
##Title: DWVGIS 2. DMAs.R
#Author: Jack Reilly
#Purpose: Illustrate loading an internal shape file (luxembourg) and and an external shape file (dma_export.shp)
#Requires: the dma_export folder (dma_export.shp with its .shx, .dbf, .prj and .cpg files), in ~/desktop/working/dwv26;
# download it from the Course Drive
library(sf)
library(terra)
library(tmap)
library(tidyverse)
library(RColorBrewer)
library(maptiles)
library(cartogram)
#Set the working directory
setwd("~/desktop/working/dwv26")
#Identify the path to the internal luxembourg data
filename <- system.file("ex/lux.shp", package="terra")
filename
#Load and draw the data
lux <- vect(filename)
class(lux)
plot(lux)
#Read and plot dma_export.shp
dmas <- st_read("dma_export/dma_export.shp")
plot(dmas)
#Show the filetypes supported by st_read
st_drivers()
#Keep just the lower 48: crop to a box around them and plot the outlines
lower48 <- st_crop(dmas, xmin = -125, xmax = -66, ymin = 24, ymax = 50)
plot(st_geometry(lower48))3. Census

dwvgis_3_census.R
##Title: DWVGIS 3. Census.R
#Author: Jack Reilly
#Purpose: Illustrate using the Census API to visualize geographic data
#Requires: no external data
library(tidyverse)
library(ggthemes)
library(tidycensus)
library(ggplot2)
library(dplyr)
library(sf)
# (Run once per computer; then restart R)
#census_api_key("YOUR KEY HERE", install = TRUE)
# Load 2020 population by county, with geometry
counties <- get_decennial(
geography = "county",
variables = "P1_001N", # total population
year = 2020,
geometry = TRUE
)
#Look at the data
counties
#Make an initial plot
ggplot(counties) +
geom_sf(aes(fill = value), color = NA) +
labs(title = "Population by County, 2020",
fill = "People") +
theme_minimal()
#Constrain graph by lat/long
ggplot(counties) +
geom_sf(aes(fill = value), color = NA) +
coord_sf(
xlim = c(-125, -66), # longitude range
ylim = c(24, 50), # latitude range
expand = FALSE
) +
labs(title = "Population by County, 2020",
fill = "People") +
theme_minimal()
# Filter out Alaska, Hawaii, Puerto Rico, etc.
counties <- counties |>
mutate(STATEFP = substr(GEOID, 1, 2)) |>
filter(!STATEFP %in% c("02", "15", "72")) # AK, HI, PR
lower48 <- counties |>
filter(!STATEFP %in% c("02", "15", "72")) # 02 = AK, 15 = HI, 72 = PR
# Project to something appropriate for U.S. maps (Albers equal area)
lower48 <- st_transform(lower48, 5070)
# Plot
ggplot(lower48) +
geom_sf(aes(fill = value), color = NA) +
coord_sf(datum = NA) +
labs(title = "Population by County, 2020",
fill = "People") +
theme_minimal()
#Let's use viridis color scheme!
ggplot(lower48) +
geom_sf(aes(fill = value), color = NA) +
scale_fill_viridis_c(labels = scales::comma) +
coord_sf(datum = NA) +
labs(title = "Population by County, 2020",
fill = "People") +
theme_minimal()
#Still not a good scale
#Fix that scale
library(scales) # for label_number(), cut_short_scale()
#Build plot like we did before
#Note the scale transform, the breaks, and the legend simplification
p <- ggplot(lower48, aes(fill = value)); p #This is already an sf object, so we don't have to declare lat/long!
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
scale_fill_viridis_c(
trans = "log10",
breaks = c(1e2, 1e3, 1e4, 1e5, 1e6, 1e7),
labels = label_number(scale_cut = cut_short_scale())
) +
labs(title = "Population by County, 2020", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))
#I'd like to squish the bottom of the scale a little bit to show more contrast. Not many counties with 100 people in them.
vmax <- max(lower48$value, na.rm = TRUE)
p <- ggplot(lower48, aes(fill = value)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
scale_fill_viridis_c(
trans = "log10",
limits = c(1e3, vmax), # start color mapping at 1,000
oob = squish, # values <1,000 get the lowest color
breaks = c(1e3, 1e4, 1e5, 1e6, 1e7),
labels = label_number(scale_cut = cut_short_scale())
) +
labs(title = "Population by County, 2020", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))
#Let's graph homeownership!
#Get the data
homeown <- get_acs(
geography = "county",
variables = c(total = "B25003_001", owners = "B25003_002"),
year = 2023,
geometry = TRUE
) |>
mutate(STATEFP = substr(GEOID, 1, 2)) |>
filter(!STATEFP %in% c("02","15","60","66","69","72","78")) |> # lower 48
st_transform(5070) |>
select(GEOID, NAME, variable, estimate, geometry) |>
tidyr::pivot_wider(names_from = variable, values_from = estimate) |>
mutate(homeown_rate = 100 * owners / total)
#Graph it
#Note different style choices on color scale: homeownership is actually kind of high, so I want more yellows
p <- ggplot(homeown, aes(fill = homeown_rate)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
scale_fill_viridis_c(
limits = c(40, 90), # focus color stretch on 40–90%
oob = squish,
breaks = seq(40, 90, by = 10),
labels = label_number(suffix = "%")
) +
labs(title = "Homeownership Rate by County, 2023", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))
#Let's graph income!
#Get the data
income <- get_acs(
geography = "county",
variables = "B19013_001", # Median household income (past 12 months)
year = 2023,
geometry = TRUE
) |>
rename(median_income = estimate) |>
mutate(STATEFP = substr(GEOID, 1, 2)) |>
filter(!STATEFP %in% c("02","15","60","66","69","72","78")) |> # lower 48 only
st_transform(5070)
#Mean and median income are both around 65k
mean(income$median_income, na.rm=T)
median(income$median_income, na.rm=T)
#Visually, I want a scale that somewhat reflects that
#I have some high outliers, though, so I still want to do somethign with the scale
#Either cap it or transform it
library(lattice)
histogram(income$median_income, na.rm=T)
# Graph it
# This version picks capping; transform command left in
p <- ggplot(income, aes(fill = median_income)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
scale_fill_viridis_c(
# trans = "log10",
limits = c(30000, 100000), # stretch around typical range
oob = squish,
breaks = c(30000, 50000, 70000, 90000, 110000),
labels = label_dollar(scale_cut = cut_short_scale())
) +
labs(title = "Median Household Income by County, 2023", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))
#Education!
#Get the data
edu <- get_acs(
geography = "county",
variables = c(
total = "B15003_001", # total population age 25+
high = "B15003_017", # high school
bach = "B15003_022", # bachelor's
mast = "B15003_023", # master's
prof = "B15003_024", # professional
doct = "B15003_025" # doctorate
),
year = 2023,
geometry = TRUE
) |>
select(GEOID, variable, estimate, geometry) |>
pivot_wider(names_from = variable, values_from = estimate) |>
mutate(
STATEFP = substr(GEOID, 1, 2),
ba_plus = 100 * (bach + mast + prof + doct) / total,
# hs_plus = 100 * (high + bach + mast + prof + doct) / total
) |>
filter(!STATEFP %in% c("02","15","60","66","69","72","78")) |> # lower 48
st_transform(5070)
# Graph it
# Here, I want my visual midpoint around 50% BA, as that creates the contrast I'm trying to illustrate
# Even though the range is a little different
mean(edu$ba_plus)
range(edu$ba_plus)
p <- ggplot(edu, aes(fill = ba_plus)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
scale_fill_viridis_c(
limits = c(10, 60), # % adults with BA+ typically in this range
oob = squish,
breaks = seq(10, 60, by = 10),
labels = label_number(suffix = "%")
) +
labs(title = "Adults 25+ with Bachelor's Degree or Higher, 2023", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))4. OpenStreetMap

dwvgis_4_osm.R
##Title: DWV - OSM Data.R
#Author: Jack Reilly
#Purpose: Street Maps with OSM
#Requires: no external data; must install osmdata within script
#Output: map PDFs, saved to ~/desktop/working/dwv26
#And ggplot2tor:
#https://ggplot2tutor.com/tutorials/streetmaps
library(remotes)
#remotes::install_github("ropensci/osmdata")
library(tidyverse)
library(osmdata) # package for working with streets
library(showtext) # for custom fonts
library(ggmap)
#library(rvest) #not needed here
#Set the working directory
setwd("~/desktop/working/dwv26")
#you can find all the available features of OSM here:
#https://wiki.openstreetmap.org/wiki/Map_features
#or here (can be slow, uncomment to see):
#available_features()
#Also use openstreemap.org to inspect features
available_tags("highway")
#getbb = "Get Bounding Box"
syrbounds<-getbb("Syracuse New York")
syrbounds
#Now we're going to pipe commands together to build our map
#Essentially: get our bounding box, <pass>, build an openstreemap query (opq), <pass>,
#add features, <pass>, return query as formatted SF object
syr_big_streets <- syrbounds %>%
opq() %>%
add_osm_feature(key = "highway",
value = c("motorway", "trunk", "primary", "motorway_link", "trunk_link", "primary_link")) %>%
osmdata_sf()
#Now let's see what we have!
syr_big_streets
#Remember - the core components of graphing. Points, Lines, Polygons (and iterations on those)
# osm_lines, osm_points, osm_polygons
#Time to do some plotting with our old friend, GGPlot
#geom_sf - plot "simple feature" objects (the kind used in GIS)
ggplot() +
geom_sf(data = syr_big_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = 1)
#Can play with aesthetics, like always
ggplot() +
geom_sf(data = syr_big_streets$osm_lines,
inherit.aes = FALSE,
color = "purple",
size = 8)
#Lets get some more data
syr_med_streets <- syrbounds%>%
opq()%>%
add_osm_feature(key = "highway",
value = c("secondary", "tertiary", "secondary_link", "tertiary_link")) %>%
osmdata_sf()
syr_small_streets <- syrbounds%>%
opq()%>%
add_osm_feature(key = "highway",
value = c("residential", "living_street",
"unclassified",
"service", "footway")) %>%
osmdata_sf()
syr_coast <- syrbounds%>%
opq()%>%
add_osm_feature(key = "natural", value="coastline") %>%
osmdata_sf()
syr_water <- syrbounds%>%
opq()%>%
add_osm_feature(key = "natural", value="water") %>%
osmdata_sf()
syr_railway <- syrbounds%>%
opq()%>%
add_osm_feature(key = "railway", value="rail") %>%
osmdata_sf()
#Let's layer all these together
ggplot() +
geom_sf(data = syr_coast$osm_polygons,
inherit.aes = FALSE,
color = "steelblue",
size = 1) +
geom_sf(data = syr_coast$osm_lines,
inherit.aes = FALSE,
color = "steelblue",
size = 1) +
geom_sf(data = syr_railway$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .2,
linetype="dotdash",
alpha = .5) +
geom_sf(data = syr_med_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .3,
alpha = .5) +
geom_sf(data = syr_small_streets$osm_lines,
inherit.aes = FALSE,
color = "#666666",
size = .2,
alpha = .3) +
geom_sf(data = syr_big_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .5,
alpha = .6) +
coord_sf(xlim = syrbounds[1,],
ylim = syrbounds[2,],
expand = FALSE)
#Very swanky. How about a title and getting rid of that chartjunk?
#Add a fancy looking font
font_add_google(name = "Lato", family = "lato") # add custom fonts
showtext_auto()
ggplot() +
geom_sf(data = syr_coast$osm_polygons,
inherit.aes = FALSE,
color = "steelblue",
size = .3,
fill = "white") +
geom_sf(data = syr_coast$osm_lines,
inherit.aes = FALSE,
color = "steelblue",
size = .3) +
geom_sf(data = syr_water$osm_polygons,
inherit.aes = FALSE,
color = "steelblue",
size = .15) +
geom_sf(data = syr_railway$osm_lines,
inherit.aes = FALSE,
color = "red",
size = .2,
linetype="dotdash",
alpha = .9) +
geom_sf(data = syr_med_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .3,
alpha = .5) +
geom_sf(data = syr_small_streets$osm_lines,
inherit.aes = FALSE,
color = "#666666",
size = .2,
alpha = .3) +
geom_sf(data = syr_big_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .5,
alpha = .6) +
coord_sf(xlim = syrbounds[1,],
ylim = syrbounds[2,],
expand = FALSE) +
theme_void() + # get rid of background color, grid lines, etc.
theme(plot.title = element_text(size = 20, family = "lato", face="bold", hjust=.5),
plot.subtitle = element_text(family = "lato", size = 8, hjust=.5, margin=margin(2, 0, 5, 0))) +
labs(title = "SYRACUSE", subtitle = "43.0481° N / 76.1474° W")
ggsave(file="Syracuse.pdf", units="in", width=6, height=7)
#Let's make this a map *of* something!
syr_fire <- syrbounds%>%
opq()%>%
add_osm_feature(key = "amenity", value=c("fire_station")) %>%
osmdata_sf()
syr_fire
ggplot() +
geom_sf(data = syr_coast$osm_polygons,
inherit.aes = FALSE,
color = "steelblue",
size = .3,
fill = "white") +
geom_sf(data = syr_coast$osm_lines,
inherit.aes = FALSE,
color = "steelblue",
size = .3) +
geom_sf(data = syr_water$osm_polygons,
inherit.aes = FALSE,
color = "steelblue",
size = .15) +
geom_sf(data = syr_railway$osm_lines,
inherit.aes = FALSE,
color = "red",
size = .2,
linetype="dotdash",
alpha = .9) +
geom_sf(data = syr_med_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .3,
alpha = .5) +
geom_sf(data = syr_small_streets$osm_lines,
inherit.aes = FALSE,
color = "#666666",
size = .2,
alpha = .3) +
geom_sf(data = syr_big_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .5,
alpha = .6) +
geom_sf(data = syr_fire$osm_points,
inherit.aes = FALSE,
color = "red4",
size = 5,
alpha = .6) +
coord_sf(xlim = syrbounds[1,],
ylim = syrbounds[2,],
expand = FALSE) +
theme_void() + # get rid of background color, grid lines, etc.
theme(plot.title = element_text(size = 20, family = "lato", face="bold", hjust=.5),
plot.subtitle = element_text(family = "lato", size = 8, hjust=.5, margin=margin(2, 0, 5, 0))) +
labs(title = "FIRE STATIONS", subtitle = "SYRACUSE")
ggsave(file="firesyracuse.pdf", units="in", width=6, height=7)
#A Smaller View
orangebounds<-getbb("Syracuse University")
is_big_streets <- orangebounds %>%
opq() %>%
add_osm_feature(key = "highway",
value = c("motorway", "primary", "motorway_link", "primary_link", "trunk", "trunk_link")) %>%
osmdata_sf()
is_med_streets <- orangebounds%>%
opq()%>%
add_osm_feature(key = "highway",
value = c("secondary", "tertiary", "secondary_link", "tertiary_link")) %>%
osmdata_sf()
is_small_streets <- orangebounds%>%
opq()%>%
add_osm_feature(key = "highway",
value = c("residential", "living_street",
"unclassified",
"service", "footway"
)) %>%
osmdata_sf()
is_railway <- orangebounds %>%
opq()%>%
add_osm_feature(key = "railway", value="rail") %>%
osmdata_sf()
ggplot() +
geom_sf(data = is_railway$osm_lines,
inherit.aes = FALSE,
color = "red",
size = .2,
linetype="dotdash",
alpha = .9) +
geom_sf(data = is_med_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .3,
alpha = .5) +
geom_sf(data = is_small_streets$osm_lines,
inherit.aes = FALSE,
color = "#666666",
size = .2,
alpha = .3) +
geom_sf(data = is_big_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .5,
alpha = .6) +
coord_sf(xlim = orangebounds[1,],
ylim = orangebounds[2,],
expand = FALSE) +
theme_void() + # get rid of background color, grid lines, etc.
theme(plot.title = element_text(size = 20, family = "lato", face="bold", hjust=.5),
plot.subtitle = element_text(family = "lato", size = 8, hjust=.5, margin=margin(2, 0, 5, 0))) +
labs(title = "SYRACUSE UNIVERSITY", subtitle = "GO ORANGE")
ggsave(file="syruniv.pdf", units="in", width=6, height=7)
5. Syracuse University
Download dwvgis_5_syracuse_university_osm.R

dwvgis_5_syracuse_university_osm.R
##Title: DWVGIS - 5. Syracuse University.R
#Author: Jack Reilly
#Purpose: Syracuse University Street Map with OSM
#Requires: no external data; must install osmdata within script
library(osmdata)
library(sf)
library(dplyr)
library(ggplot2)
main_bb <- c(
left = -76.1435,
bottom = 43.0330,
right = -76.1215,
top = 43.0445
)
# Helper: safely handle possibly NULL layers
safe_sf <- function(x, crs = 4326) {
if (is.null(x)) st_sf(geometry = st_sfc(crs = crs))[0, ]
else suppressWarnings(st_make_valid(x))
}
# ---- Queries (bounded by bbox; no clipping) ----
is_big_streets <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("primary","trunk","primary_link","trunk_link")) |>
osmdata_sf()
is_med_streets <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("secondary","tertiary","secondary_link","tertiary_link")) |>
osmdata_sf()
is_small_streets <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("residential","service","unclassified")) |>
osmdata_sf()
is_ped <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("footway","path","pedestrian","steps")) |>
osmdata_sf()
is_buildings <- opq(bbox = main_bb) |>
add_osm_feature("building") |>
osmdata_sf()
is_green <- opq(bbox = main_bb) |>
add_osm_feature("landuse", c("grass","park","recreation_ground")) |>
osmdata_sf()
is_parking <- opq(bbox = main_bb) |>
add_osm_feature("amenity", "parking") |>
osmdata_sf()
# ---- Extract layers safely ----
bldg_poly <- safe_sf(is_buildings$osm_polygons)
bldg_mpoly <- safe_sf(is_buildings$osm_multipolygons)
green_poly <- safe_sf(is_green$osm_polygons)
green_mpoly <- safe_sf(is_green$osm_multipolygons)
park_poly <- safe_sf(is_parking$osm_polygons)
park_mpoly <- safe_sf(is_parking$osm_multipolygons)
ln_big <- safe_sf(is_big_streets$osm_lines)
ln_med <- safe_sf(is_med_streets$osm_lines)
ln_small <- safe_sf(is_small_streets$osm_lines)
ln_ped <- safe_sf(is_ped$osm_lines)
sview_bb <- c(
left = -76.1390,
bottom = 43.035,
right = -76.128,
top = 43.043
)
# ---- Plot ----
ggplot() +
# Greenspace
geom_sf(data = green_poly, fill = "#DDEBD2", color = NA, alpha = 0.7) +
geom_sf(data = green_mpoly, fill = "#DDEBD2", color = NA, alpha = 0.7) +
# Parking
geom_sf(data = park_poly, fill = "#EFE9E4", color = NA, alpha = 0.9) +
geom_sf(data = park_mpoly, fill = "#EFE9E4", color = NA, alpha = 0.9) +
# Roads
geom_sf(data = ln_ped, color = "#A7ADB4", linewidth = 0.25, alpha = 0.8) +
geom_sf(data = ln_small, color = "#5C636A", linewidth = 0.35, alpha = 0.6) +
geom_sf(data = ln_med, color = "#5C636A", linewidth = 0.6, alpha = 0.8) +
geom_sf(data = ln_big, color = "#0D2D6C", linewidth = 0.9, alpha = 0.9) +
# Buildings
geom_sf(data = bldg_poly, fill = "#F76900", color = "#8A3B00", linewidth = 0.18, alpha = 0.95) +
geom_sf(data = bldg_mpoly, fill = "#F76900", color = "#8A3B00", linewidth = 0.18, alpha = 0.95) +
# Frame map extent
coord_sf(xlim = c(sview_bb["left"], sview_bb["right"]),
ylim = c(sview_bb["bottom"], sview_bb["top"]),
expand = FALSE) +
theme_void() +
labs(title = "Syracuse University — Main Campus",
subtitle = "Brochure-style map (buildings, roads, green, parking)")
ggplot() +
# Greenspace
geom_sf(data = green_poly, fill = "#DDEBD2", color = NA, alpha = 0.7) +
geom_sf(data = green_mpoly, fill = "#DDEBD2", color = NA, alpha = 0.7) +
# Parking
geom_sf(data = park_poly, fill = "#EFE9E4", color = NA, alpha = 0.9) +
geom_sf(data = park_mpoly, fill = "#EFE9E4", color = NA, alpha = 0.9) +
# Roads
geom_sf(data = ln_ped, color = "#A7ADB4", linewidth = 0.25, alpha = 0.8) +
geom_sf(data = ln_small, color = "#5C636A", linewidth = 0.35, alpha = 0.6) +
geom_sf(data = ln_med, color = "#5C636A", linewidth = 0.6, alpha = 0.8) +
geom_sf(data = ln_big, color = "#0D2D6C", linewidth = 0.9, alpha = 0.9) +
# Buildings
geom_sf(data = bldg_poly, fill = "#F76900", color = "#8A3B00", linewidth = 0.18, alpha = 0.95) +
geom_sf(data = bldg_mpoly, fill = "#F76900", color = "#8A3B00", linewidth = 0.18, alpha = 0.95) +
# Frame map extent
coord_sf(xlim = c(sview_bb["left"], sview_bb["right"]),
ylim = c(sview_bb["bottom"], sview_bb["top"]),
expand = FALSE) +
theme(plot.title = element_text(size = 20, family = "lato", face="bold", hjust=.5),
plot.subtitle = element_text(family = "lato", size = 8, hjust=.5, margin=margin(2, 0, 5, 0))) +
labs(title = "SYRACUSE UNIVERSITY", subtitle = "CORE CAMPUS")
6. Maxwell and Eggers
Download dwvgis_6_maxwell_eggers.R

dwvgis_6_maxwell_eggers.R
##Title: DWVGIS - 6. Maxwell Eggers Hall.R
#Author: Jack Reilly
#Purpose: Syracuse University/Maxwell Street Map with OSM
#Requires: no external data; must install osmdata within script
library(osmdata)
library(sf)
library(dplyr)
library(ggplot2)
#The bounding box for our query
main_bb <- c(
left = -76.1435,
bottom = 43.0330,
right = -76.1215,
top = 43.0445
)
#The bounding box for our final view
sview_bb <- c(
left = -76.1410,
bottom = 43.0335,
right = -76.1225,
top = 43.0438
)
safe_sf <- function(x, crs = 4326) {
if (is.null(x)) st_sf(geometry = st_sfc(crs = crs))[0, ]
else suppressWarnings(st_make_valid(x))
}
# ---- Queries ----
is_big_streets <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("primary","trunk","primary_link","trunk_link")) |>
osmdata_sf()
is_med_streets <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("secondary","tertiary","secondary_link","tertiary_link")) |>
osmdata_sf()
is_small_streets <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("residential","service","unclassified")) |>
osmdata_sf()
is_ped <- opq(bbox = main_bb) |>
add_osm_feature("highway", c("footway","path","pedestrian","steps")) |>
osmdata_sf()
is_buildings <- opq(bbox = main_bb) |>
add_osm_feature("building") |>
osmdata_sf()
is_green <- opq(bbox = main_bb) |>
add_osm_feature("landuse", c("grass","park","recreation_ground")) |>
osmdata_sf()
is_parking <- opq(bbox = main_bb) |>
add_osm_feature("amenity", "parking") |>
osmdata_sf()
# ---- Extract layers ----
bldg_poly <- safe_sf(is_buildings$osm_polygons)
bldg_mpoly <- safe_sf(is_buildings$osm_multipolygons)
green_poly <- safe_sf(is_green$osm_polygons)
green_mpoly <- safe_sf(is_green$osm_multipolygons)
park_poly <- safe_sf(is_parking$osm_polygons)
park_mpoly <- safe_sf(is_parking$osm_multipolygons)
ln_big <- safe_sf(is_big_streets$osm_lines)
ln_med <- safe_sf(is_med_streets$osm_lines)
ln_small <- safe_sf(is_small_streets$osm_lines)
ln_ped <- safe_sf(is_ped$osm_lines)
# ---- Identify Maxwell & Eggers ----
# Combine polygons and multipolygons for search
bldgs_all <- bind_rows(bldg_poly, bldg_mpoly)
# Check what OSM calls them (optional):
# unique(bldgs_all$name)
bldgs_all <- bldgs_all |>
mutate(
name_lower = tolower(name),
highlight = ifelse(
str_detect(name_lower, "maxwell") | str_detect(name_lower, "eggers"),
"highlight", "normal"
)
)
# ---- Plot ----
ggplot() +
# Greenspace
geom_sf(data = green_poly, fill = "#DDEBD2", color = NA, alpha = 0.7) +
geom_sf(data = green_mpoly, fill = "#DDEBD2", color = NA, alpha = 0.7) +
# Parking
geom_sf(data = park_poly, fill = "#EFE9E4", color = NA, alpha = 0.9) +
geom_sf(data = park_mpoly, fill = "#EFE9E4", color = NA, alpha = 0.9) +
# Roads
geom_sf(data = ln_ped, color = "#A7ADB4", linewidth = 0.25, alpha = 0.8) +
geom_sf(data = ln_small, color = "#5C636A", linewidth = 0.35, alpha = 0.6) +
geom_sf(data = ln_med, color = "#5C636A", linewidth = 0.6, alpha = 0.8) +
geom_sf(data = ln_big, color = "#0D2D6C", linewidth = 0.9, alpha = 0.9) +
# Buildings — blue for all, orange for Maxwell/Eggers
geom_sf(data = bldgs_all |> filter(highlight == "normal"),
fill = "#90CAF9", color = "#234E70", linewidth = 0.18, alpha = 0.95) +
geom_sf(data = bldgs_all |> filter(highlight == "highlight"),
fill = "#F76900", color = "#8A3B00", linewidth = 0.25, alpha = 0.95) +
coord_sf(xlim = c(sview_bb["left"], sview_bb["right"]),
ylim = c(sview_bb["bottom"], sview_bb["top"]),
expand = FALSE) +
theme_void() +
labs(
title = "Syracuse University — Main Campus",
subtitle = "Maxwell & Eggers Hall highlighted in orange"
)7. Kaua’i

dwvgis_7_kauai.R
##Title: DWVGIS - 7. Kauai Island OSM.R
#Author: Jack Reilly
#Purpose: Draw Kauai Island
#Requires: no external data; must install osmdata within script
library(osmdata)
library(sf)
library(dplyr)
library(ggplot2)
kauaibb<-getbb("Kauai")
is_coast <- kauaibb %>%
opq()%>%
add_osm_feature(key = "natural", value="coastline") %>%
osmdata_sf()
is_water <- kauaibb%>%
opq()%>%
add_osm_feature(key = "natural", value="water") %>%
osmdata_sf()
is_big_streets <- kauaibb %>%
opq() %>%
add_osm_feature(key = "highway",
value = c("motorway", "trunk", "primary", "motorway_link", "primary_link", "trunk_link")) %>%
osmdata_sf()
is_med_streets <- kauaibb%>%
opq()%>%
add_osm_feature(key = "highway",
value = c("secondary", "tertiary", "secondary_link", "tertiary_link")) %>%
osmdata_sf()
is_small_streets <- kauaibb%>%
opq()%>%
add_osm_feature(key = "highway",
value = c("residential", "living_street",
"unclassified",
"service", "footway"
)) %>%
osmdata_sf()
is_river <- kauaibb%>%
opq()%>%
add_osm_feature(key = "waterway", value = "river") %>%
osmdata_sf()
is_railway <- kauaibb %>%
opq()%>%
add_osm_feature(key = "railway", value="rail") %>%
osmdata_sf()
ggplot() +
geom_sf(data = is_coast$osm_lines,
inherit.aes = FALSE,
color = "green4",
size = 1)
ggplot() +
geom_sf(data = is_coast$osm_lines,
inherit.aes = FALSE,
color = "steelblue",
size = .3) +
geom_sf(data = is_water$osm_polygons,
inherit.aes = FALSE,
color = "steelblue",
size = .15,
fill = "white") +
geom_sf(data = is_railway$osm_lines,
inherit.aes = FALSE,
color = "red",
size = .2,
linetype="dotdash",
alpha = .9) +
geom_sf(data = is_med_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .3,
alpha = .5) +
geom_sf(data = is_small_streets$osm_lines,
inherit.aes = FALSE,
color = "#666666",
size = .2,
alpha = .3) +
geom_sf(data = is_big_streets$osm_lines,
inherit.aes = FALSE,
color = "black",
size = .5,
alpha = .6) +
coord_sf(xlim = kauaibb[1,],
ylim = kauaibb[2,],
expand = FALSE) +
theme_void() + # get rid of background color, grid lines, etc.
theme(plot.title = element_text(size = 20, family = "lato", face="bold", hjust=.5),
plot.subtitle = element_text(family = "lato", size = 8, hjust=.5, margin=margin(2, 0, 5, 0))) +
labs(title = "KAUA'I", subtitle = "HAWAI'I")
setwd("~/desktop/working/dwv26")
ggsave(file="kauai.pdf", units="in", width=6, height=7)8. Crater Lake
- Mac users: install XQuartz first, then restart your computer.
rayshaderloads therglpackage, which on a Mac needs XQuartz’s graphics libraries; without it,library(rayshader)fails at once with an error that mentionsrgl.soandlibGLU.1.dylib. Windows needs nothing extra. - Use a current R and current packages.
rayshader,rayimageandrayrenderare updated together, and a mismatched set fails with errors like'add_image_overlay' is not an exported object from 'namespace:rayimage'. The currentrayshadercomes ready-built only for recent R (4.5 or newer); on an older R,install.packages("rayshader")gives you an old version or tries to compile it. If that happens, update R, then runupdate.packages(). Both scripts need a recentrayimage(they useray_read_image()). - Be patient. The elevation file is 5,200 by 5,200 cells. The scripts shrink it first, but the shading still takes a minute or so, and
ambient_shade()is the slowest step. The extended script’s 3D view (plot_3d()) opens a separate window.
Download dwvgis_8_crater_lake.R

dwvgis_8_crater_lake.R
#https://www.tylermw.com/posts/data_visualization/adding-open-street-map-data-to-rayshader-maps-in-r.html
library(rayshader)
library(raster)
library(sf)
library(osmdata)
library(dplyr)
library(ggplot2)
library(magick)
crater = raster('~/desktop/working/dwv26/Crater_Lake.tif')
crater_mat = raster_to_matrix(crater)
crater_small = resize_matrix(crater_mat,0.25)
#The desert texture, made once and used in each map below.
#ray_read_image() gives it the transparency channel that current versions
#of rayshader need before add_overlay() can blend it in.
desert = sphere_shade(crater_small, texture = "desert",
zscale=4, colorintensity = 5) %>%
rayimage::ray_read_image(convert_to_array = TRUE)
crater_small %>%
height_shade() %>%
plot_map()
crater_small %>%
height_shade() %>%
add_overlay(desert, alphalayer=0.5) %>%
plot_map()
crater_small %>%
height_shade() %>%
add_overlay(desert, alphalayer=0.5) %>%
add_shadow(lamb_shade(crater_small,zscale = 6),0) %>%
plot_map()
crater_small %>%
height_shade() %>%
add_overlay(desert, alphalayer=0.5) %>%
add_shadow(lamb_shade(crater_small,zscale=6), 0) %>%
add_shadow(texture_shade(crater_small,detail=8/10,contrast=9,brightness = 11), 0.1) %>%
plot_map()
crater_small %>%
height_shade() %>%
add_overlay(desert, alphalayer=0.5) %>%
add_shadow(lamb_shade(crater_small,zscale=6), 0) %>%
add_shadow(ambient_shade(crater_small), 0) %>%
add_shadow(texture_shade(crater_small,detail=8/10,contrast=9,brightness = 11), 0.1) %>%
plot_map()The extended version builds the same map step by step, then adds water, roads, trails, Mount Scott, the park boundary and a 3D view, all from OpenStreetMap:
Download dwvgis_8_crater_lake_rev.R

dwvgis_8_crater_lake_rev.R
# Crater Lake: Terrain Shading
# https://www.tylermw.com/posts/data_visualization/adding-open-street-map-data-to-rayshader-maps-in-r.html
library(rayshader)
library(raster)
library(sf)
library(osmdata)
library(dplyr)
library(ggplot2)
library(magick)
# --------------------------------------------------
# 1. Load and prepare elevation data
# --------------------------------------------------
crater <- raster(
"~/desktop/working/dwv26/Crater_Lake.tif"
)
crater_mat <- raster_to_matrix(crater)
crater_small <- resize_matrix(crater_mat, 0.25)
# --------------------------------------------------
# 2. Generate shading layers
# --------------------------------------------------
# Basic elevation shading
base_map <- height_shade(crater_small)
# Desert texture with an explicit alpha channel
desert_overlay <- sphere_shade(
crater_small,
texture = "desert",
zscale = 4,
colorintensity = 5
) %>%
rayimage::ray_read_image(convert_to_array = TRUE)
# Lambertian shading
lamb_shadow <- lamb_shade(
crater_small,
zscale = 6
)
# Fine terrain texture
texture_shadow <- texture_shade(
crater_small,
detail = 0.8,
contrast = 9,
brightness = 11
)
# Ambient occlusion shading
ambient_shadow <- ambient_shade(crater_small)
# --------------------------------------------------
# 3. Map 1: Basic elevation shading
# --------------------------------------------------
base_map %>%
plot_map()
# --------------------------------------------------
# 4. Map 2: Add desert texture
# --------------------------------------------------
base_map %>%
add_overlay(
desert_overlay,
alphalayer = 0.5
) %>%
plot_map()
# --------------------------------------------------
# 5. Map 3: Add Lambertian shading
# --------------------------------------------------
base_map %>%
add_overlay(
desert_overlay,
alphalayer = 0.5
) %>%
add_shadow(lamb_shadow, max_darken = 0) %>%
plot_map()
# --------------------------------------------------
# 6. Map 4: Add fine terrain texture
# --------------------------------------------------
base_map %>%
add_overlay(
desert_overlay,
alphalayer = 0.5
) %>%
add_shadow(lamb_shadow, max_darken = 0) %>%
add_shadow(texture_shadow, max_darken = 0.1) %>%
plot_map()
# --------------------------------------------------
# 7. Map 5: Add ambient occlusion
# --------------------------------------------------
base_map %>%
add_overlay(
desert_overlay,
alphalayer = 0.5
) %>%
add_shadow(lamb_shadow, max_darken = 0) %>%
add_shadow(ambient_shadow, max_darken = 0) %>%
add_shadow(texture_shadow, max_darken = 0.1) %>%
plot_map()
# --------------------------------------------------
# 8. Map 6: Add blue water
# --------------------------------------------------
# Identify water surfaces
water_map <- detect_water(
crater_small,
min_area = 100
)
base_map %>%
add_overlay(
desert_overlay,
alphalayer = 0.5
) %>%
add_shadow(lamb_shadow, max_darken = 0) %>%
add_shadow(ambient_shadow, max_darken = 0) %>%
add_shadow(texture_shadow, max_darken = 0.1) %>%
add_water(water_map, color = "#2471A3") %>%
plot_map()
# Better water!
# --------------------------------------------------
# 8. Map 6: Add water from OpenStreetMap
# --------------------------------------------------
# Get the geographic extent of our elevation raster
crater_bbox <- st_bbox(
c(
xmin = xmin(crater),
ymin = ymin(crater),
xmax = xmax(crater),
ymax = ymax(crater)
),
crs = st_crs(projection(crater))
)
# Convert bounding box to latitude/longitude for OSM
osm_bbox <- crater_bbox %>%
st_as_sfc() %>%
st_transform(4326) %>%
st_bbox()
# Download water features from OpenStreetMap
osm_water <- opq(bbox = osm_bbox) %>%
add_osm_feature(key = "natural", value = "water") %>%
osmdata_sf()
# Combine ordinary polygons and multipolygons
water_polygons <- bind_rows(
select(osm_water$osm_polygons, geometry),
select(osm_water$osm_multipolygons, geometry)
)
# Match the coordinate system of the elevation raster
water_polygons <- water_polygons %>%
st_transform(st_crs(projection(crater)))
# Convert OSM water polygons to a blue image overlay
water_overlay <- generate_polygon_overlay(
water_polygons,
extent = extent(crater),
heightmap = crater_small,
palette = "#2471A3",
linewidth = NA
)
# Draw the map with the water overlay
base_map %>%
add_overlay(desert_overlay, alphalayer = 0.5) %>%
add_shadow(lamb_shadow, max_darken = 0) %>%
add_shadow(ambient_shadow, max_darken = 0) %>%
add_shadow(texture_shadow, max_darken = 0.1) %>%
add_overlay(water_overlay) %>%
plot_map()
# --------------------------------------------------
# 8. Map 6: OSM lakes and streams
# --------------------------------------------------
map_crs <- st_crs(projection(crater))
# 1. Separate water multipolygons from ordinary polygons
water_multi <- osm_water$osm_multipolygons %>%
filter(natural == "water") %>%
st_transform(map_crs)
water_simple <- osm_water$osm_polygons %>%
filter(natural == "water") %>%
st_transform(map_crs)
# 2. Keep multipolygons (which preserve island holes)
# and ordinary polygons that do not overlap them
if (nrow(water_multi) == 0) {
stop("No water multipolygons found in OSM data.")
}
water_simple <- water_simple[
lengths(st_intersects(water_simple, water_multi)) == 0,
]
water_polygons <- rbind(
st_sf(geometry = st_geometry(water_multi)),
st_sf(geometry = st_geometry(water_simple))
)
# 3. Create blue lake overlay
water_overlay <- generate_polygon_overlay(
water_polygons,
extent = extent(crater),
heightmap = crater_small,
palette = "#2471A3",
linewidth = NA
)
# 4. Download streams and other waterways
osm_streams <- opq(bbox = osm_bbox) %>%
add_osm_feature(
key = "waterway",
value = c("stream", "river", "ditch", "drain")
) %>%
osmdata_sf()
streams <- osm_streams$osm_lines %>%
filter(waterway %in% c("stream", "river", "ditch", "drain")) %>%
st_transform(map_crs)
# 5. Generate stream overlay
stream_overlay <- NULL
if (nrow(streams) > 0) {
stream_overlay <- generate_line_overlay(
streams,
extent = extent(crater),
heightmap = crater_small,
color = "#2471A3",
linewidth = 2
)
}
# 6. Draw final map
final_map <- base_map %>%
add_overlay(desert_overlay, alphalayer = 0.5) %>%
add_shadow(lamb_shadow, max_darken = 0) %>%
add_shadow(ambient_shadow, max_darken = 0) %>%
add_shadow(texture_shadow, max_darken = 0.1) %>%
add_overlay(water_overlay)
if (!is.null(stream_overlay)) {
final_map <- final_map %>%
add_overlay(stream_overlay)
}
final_map %>%
plot_map()
# --------------------------------------------------
# 9. Map 7: Add Rim Drive with a black outline
# --------------------------------------------------
# Download roads from OpenStreetMap
osm_roads <- opq(bbox = osm_bbox) %>%
add_osm_feature(key = "highway") %>%
osmdata_sf()
# Select East and West Rim Drive
rim_road <- osm_roads$osm_lines %>%
filter(
!is.na(name),
grepl("Rim Drive|Rim Dr", name, ignore.case = TRUE)
) %>%
st_transform(map_crs)
# Check that OSM returned the road
if (nrow(rim_road) == 0) {
stop("Rim Drive not found. Check OSM road names.")
}
# Black outline (wider line)
road_outline <- generate_line_overlay(
rim_road,
extent = extent(crater),
heightmap = crater_small,
color = "black",
linewidth = 5
)
# White road (narrower line)
road_white <- generate_line_overlay(
rim_road,
extent = extent(crater),
heightmap = crater_small,
color = "white",
linewidth = 2.5
)
# Add road layers to Map 6
final_map %>%
add_overlay(road_outline) %>%
add_overlay(road_white) %>%
plot_map()
# --------------------------------------------------
# 10. Map 8: Roads, hiking trails, and Mount Scott
# --------------------------------------------------
# 1. Separate roads and hiking trails
all_routes <- osm_roads$osm_lines %>%
st_transform(map_crs)
# Hiking paths and pedestrian trails
trails <- all_routes %>%
filter(highway %in% c(
"path", "footway", "steps", "bridleway", "pedestrian"
))
# Other roads, excluding Rim Drive
other_roads <- all_routes %>%
filter(highway %in% c(
"primary", "secondary", "tertiary",
"unclassified", "residential",
"service", "track", "road"
)) %>%
filter(!grepl(
"Rim Drive|Rim Dr",
coalesce(name, ""),
ignore.case = TRUE
))
# 2. Draw other roads with thinner white/black styling
other_road_outline <- generate_line_overlay(
other_roads,
extent = extent(crater),
heightmap = crater_small,
color = "black",
linewidth = 3
)
other_road_white <- generate_line_overlay(
other_roads,
extent = extent(crater),
heightmap = crater_small,
color = "white",
linewidth = 1.5
)
# 3. Draw trails as thin dashed black lines
trail_overlay <- generate_line_overlay(
trails,
extent = extent(crater),
heightmap = crater_small,
color = "black",
linewidth = 1.5,
lty = 2
)
# 4. Locate Mount Scott (USGS summit coordinates)
mt_scott <- st_as_sf(
data.frame(
lon = -122.0160296,
lat = 42.9229346
),
coords = c("lon", "lat"),
crs = 4326
) %>%
st_transform(map_crs)
scott_xy <- st_coordinates(mt_scott)
# Verify the summit falls within the raster
if (
scott_xy[1, 1] < xmin(crater) ||
scott_xy[1, 1] > xmax(crater) ||
scott_xy[1, 2] < ymin(crater) ||
scott_xy[1, 2] > ymax(crater)
) {
warning("Mount Scott is outside the elevation raster extent.")
}
# 5. Create a white triangle with red outline
# Using a transparent PNG allows separate fill
# and border colors for the point symbol.
marker_file <- tempfile(fileext = ".png")
png(
marker_file,
width = nrow(crater_small),
height = ncol(crater_small),
bg = "transparent"
)
par(mar = c(0, 0, 0, 0))
plot(
NA,
xlim = c(xmin(crater), xmax(crater)),
ylim = c(ymin(crater), ymax(crater)),
xaxs = "i", yaxs = "i",
axes = FALSE,
xlab = "", ylab = "",
type = "n"
)
points(
scott_xy[1, 1],
scott_xy[1, 2],
pch = 24,
bg = "white",
col = "#CC2222",
lwd = 2,
cex = 2
)
dev.off()
scott_overlay <- png::readPNG(marker_file)
# 6. Draw the completed map
final_map %>%
add_overlay(trail_overlay) %>%
add_overlay(other_road_outline) %>%
add_overlay(other_road_white) %>%
add_overlay(road_outline) %>%
add_overlay(road_white) %>%
add_overlay(scott_overlay) %>%
plot_map()
###################
# --------------------------------------------------
# 11. Map 9: Park boundary, darker water, and title
# --------------------------------------------------
# 1. Darken the lake
dark_water_overlay <- generate_polygon_overlay(
water_polygons,
extent = extent(crater),
heightmap = crater_small,
palette = "#1E5F8A",
linewidth = NA
)
# 2. Download Crater Lake National Park boundary
# OSM relation ID: 1274747
park_osm <- opq_osm_id(
id = "1274747",
type = "relation",
timeout = 90
) %>%
opq_string() %>%
osmdata_sf()
# 3. Extract the park boundary
if (!is.null(park_osm$osm_multipolygons) &&
nrow(park_osm$osm_multipolygons) > 0) {
park_boundary <- st_sf(
geometry = st_boundary(
st_geometry(park_osm$osm_multipolygons)
)
)
} else if (!is.null(park_osm$osm_multilines) &&
nrow(park_osm$osm_multilines) > 0) {
park_boundary <- park_osm$osm_multilines
} else {
stop("Could not extract the OSM park boundary.")
}
park_boundary <- park_boundary %>%
st_transform(map_crs)
# 4. Generate a thick brown boundary line
boundary_overlay <- generate_line_overlay(
park_boundary,
extent = extent(crater),
heightmap = crater_small,
color = "#75472B",
linewidth = 5
)
# 5. Rebuild the map with all existing features
map9 <- final_map %>%
add_overlay(dark_water_overlay) %>%
add_overlay(trail_overlay) %>%
add_overlay(other_road_outline) %>%
add_overlay(other_road_white) %>%
add_overlay(road_outline) %>%
add_overlay(road_white) %>%
add_overlay(boundary_overlay) %>%
add_overlay(scott_overlay)
# 6. Add white title in the upper left
map9 %>%
plot_map(
title_text = "Crater Lake National Park",
title_color = "white",
title_size = 60,
title_font = "sans",
title_style = "bold",
title_offset = c(22, 22)
)
#################
#################
# --------------------------------------------------
# 12. Map 10: Slightly tilted 3D perspective
# --------------------------------------------------
map9 %>%
plot_3d(
crater_small,
zscale = 6,
theta = 20,
phi = 70,
zoom = 0.75,
fov = 0,
windowsize = c(1200, 900),
background = "#202020",
solid = FALSE
)
# Bank the view: a lower camera angle lets the shaded relief stand out
render_camera(theta = 20, phi = 35, zoom = 0.6)
render_snapshot(
title_text = "Crater Lake National Park",
title_color = "white",
title_size = 30,
title_offset = c(25, 25)
)Rayshader, has a package, can make some incredible graphs and maps, and we’ve only scratched the surface. See the rayshader for this week for other external tutorials and guides. Trace those rays!1
Footnotes
Just remember to not go too wild in an actual graph. Some of what rayshader does looks very cool, but remember the Tufte aphorism: the focus of your graphs should be the data you are visualizing, not the production process behind your graph.↩︎