## `geom_smooth()` using formula = 'y ~ x'
Code:
# Installing and loading required packages
if (!require("tidyverse")) install.packages("tidyverse")
if (!require("tidycensus")) install.packages("tidycensus")
if (!require("sf")) install.packages("sf")
if (!require("mapview")) install.packages("mapview")
if (!require("leaflet")) install.packages("leaflet")
if (!require("leaflet.extras2")) install.packages("leaflet.extras2")
library(tidyverse)
library(tidycensus)
library(sf)
library(mapview)
library(leaflet)
library(leafpop)
options(scipen = 999)
# Transmitting API key
census_api_key("494018a70f114d4f76b10537730ccc9c7dbfe36b")
# Fetching ACS codebooks
ProfileTables <- load_variables(2021, "acs5/profile", cache = TRUE)
# Specifying target variables
VariableList =
c(Estimate_ = "DP05_0037P")
# Fetching the 2021 data
mydata <- get_acs(
geography = "congressional district",
state = c("TN"),
variables = VariableList,
year = 2021,
survey = "acs1",
output = "wide",
geometry = TRUE)
mydata <- rename(mydata, Area = NAME,
Estimate = Estimate_E,
Range = Estimate_M)
# Mapping the 2021 data
Map2021 <- mapview(
mydata,
zcol = "Estimate",
layer.name = "Pct. White",
popup = popupTable(
mydata,
feature.id = FALSE,
row.numbers = FALSE,
zcol = c("Area", "Estimate", "Range")
)
)
Map2021
# Plotting the 2021 data
mygraph2021 <- ggplot(mydata, aes(x = Estimate, y = reorder(Area, Estimate))) +
geom_errorbarh(aes(xmin = Estimate - Range, xmax = Estimate + Range)) +
geom_point(size = 3, color = "#099d91") +
theme_minimal(base_size = 12.5) +
labs(title = "Estimates by area",
subtitle = "Brackets show error margins.",
x = "Pct. white in 2021",
y = "")
mygraph2021
# Fetching the 2022 data
mydata <- get_acs(
geography = "congressional district",
state = c("TN"),
variables = VariableList,
year = 2022,
survey = "acs1",
output = "wide",
geometry = TRUE)
mydata <- rename(mydata, Area = NAME,
Estimate = Estimate_E,
Range = Estimate_M)
# Mapping the 2022 data
Map2022 <- mapview(
mydata,
zcol = "Estimate",
layer.name = "Pct. White",
popup = popupTable(
mydata,
feature.id = FALSE,
row.numbers = FALSE,
zcol = c("Area", "Estimate", "Range")
)
)
Map2022
# Plotting the 2022 data
mygraph2022 <- ggplot(mydata, aes(x = Estimate, y = reorder(Area, Estimate))) +
geom_errorbarh(aes(xmin = Estimate - Range, xmax = Estimate + Range)) +
geom_point(size = 3, color = "#099d91") +
theme_minimal(base_size = 12.5) +
labs(title = "Estimates by area",
subtitle = "Brackets show error margins.",
x = "Pct. white in 2022",
y = "")
mygraph2022
# Reading the data
Davidson2024 <- read.csv("https://github.com/drkblake/Data/raw/refs/heads/main/Davidson2024.csv")
# Plotting the support by minority data
ggplot(Davidson2024, aes(x = Pct_Nonwhite,
y = Pct_Harris,
color = Winner)) +
geom_point() +
geom_smooth(method = "lm",
se = FALSE) +
labs(x = "Pct. minority",
y = "Pct. Harris",
color = "Winner",
title = "Support for Harris, by percent minority, 2024") +
scale_color_brewer(palette = "Dark2")