#install.packages("sf")
#install.packages("leaflet")
#install.packages("leaflet.extras")
#install.packages("dbscan")
#install.packages("OpenStreetMap")
#install.packages("geosphere")Data 101 Mapping 1
Leaflet:
Following in part a tutorial by Lisa Lendway
# for loading our data
library(tidyverse)── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ ggplot2 3.4.4 ✔ tibble 3.2.1
✔ lubridate 1.9.3 ✔ tidyr 1.3.1
✔ purrr 1.0.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(sf)Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
# for plotting
library(leaflet)
library(leaflet.extras)
# for more stuff
library(dbscan)
Attaching package: 'dbscan'
The following object is masked from 'package:stats':
as.dendrogram
library(OpenStreetMap)
library(geosphere)library("usdata")county <- county_2019getwd()[1] "/Users/gimle/Desktop/Data 101/Data101_Mapping"
Here I am dowloading a shapefile from Marylands open data website.
https://data-maryland.opendata.arcgis.com/datasets/maryland::maryland-physical-boundaries-county-boundaries-generalized/explore?location=39.450225%2C-74.122160%2C7.60
One thing to keep in mind is that you want to link to the entire folder, which contains several documents, but they do not work unless they are all in the same file folder.
md <- st_read("/Users/gimle/Desktop/Maryland_Physical_Boundaries_-_County_Boundaries_(Generalized)", quiet = TRUE)# This dataset does not work without this transformation which I found online.
md_new <- st_transform(md, crs = 4326)md_county <- county |> filter(state == "Maryland")md_county <- md_county |>
mutate(name = str_replace(name, " County$", ""))md_pop <- md_county |>
select(c(name, pop, unemployment_rate, uninsured, hs_grad)) |>
rename(county = name)# There is one problem in this new table, the word "city" is uncapitalized in the row "Baltimore City", this is how I fix that:
md_pop$county <- gsub("city", "City", md_pop$county, fixed = TRUE)md_joined <- left_join(md_new, md_pop, by = "county")big_county <- county_completepal <- colorNumeric("viridis", domain = md_joined$pop)leaflet(md_joined) |>
addTiles() |>
addPolygons(
fillColor = ~pal(pop),
fillOpacity = 0.7,
# color = "transparent", # an alternative way of doing the same as stroke = FALSE
stroke = FALSE,
label = ~paste(str_to_title(county), ":", round(pop,0), .sep = ""),
highlight = highlightOptions(
color = "block",
fillOpacity = .9,
bringToFront = FALSE)) |>
addLegend(position = "bottomright",
pal = pal,
values = ~pop,
title = "Population")