Skip to content

Instantly share code, notes, and snippets.

@USMortality
Last active October 25, 2024 00:12
Show Gist options
  • Save USMortality/9a1c2b2a3ae8f373462f2c3287f8e7f1 to your computer and use it in GitHub Desktop.
Save USMortality/9a1c2b2a3ae8f373462f2c3287f8e7f1 to your computer and use it in GitHub Desktop.
Umfragen & Wahlergebnisse [Brandenburg, Germany]
library(rvest)
library(dplyr)
library(ggplot2)
library(tidyr)
library(scales)
sf <- 2
width <- 600 * sf
height <- 335 * sf
options(vsc.dev.args = list(width = width, height = height, res = 72 * sf))
custom_colors <- c(
"CDU" = "#000000",
"SPD" = "#E3000F",
"GRÜNE" = "#64BC5C",
"FDP" = "#FFCC00",
"LINKE" = "#BE3075",
"AfD" = "#0C1C8C",
"BVB/FW" = "#f49800",
"BSW" = "#792350"
)
url <- "https://www.wahlrecht.de/umfragen/landtage/brandenburg.htm"
webpage <- read_html(url)
tables <- html_table(webpage, fill = TRUE)
process_table <- function(tbl, rows_to_remove) {
tbl |>
select(4, 6:(ncol(tbl) - 1)) |>
slice(-rows_to_remove) |>
mutate(
Datum = as.Date(Datum, format = "%d.%m.%Y"),
across(
-Datum,
~ as.numeric(gsub(",", ".", gsub(" %", "", .))) / 100
)
)
}
ts1 <- process_table(tables[[2]], c(1, 2))
ts2 <- process_table(tables[[3]], 1:5)
ts <- bind_rows(ts1, ts2) |>
pivot_longer(cols = -Datum, names_to = "Partei") |>
filter(Partei != "PIRATEN") |>
mutate(Partei = factor(Partei, levels = names(custom_colors)))
# Create the plot
chart <- ggplot(
ts |> filter(Datum > as.Date("2014-01-01")),
aes(x = Datum, y = value, color = Partei, fill = Partei)
) +
geom_smooth(method = "loess", alpha = 0.2) + # Confidence intervals with matching fill
geom_point(size = 0.1) + # Scatter points
scale_y_continuous(labels = percent_format(scale = 100)) + # Y-axis as percentages
scale_color_manual(values = custom_colors) + # Set line colors
scale_fill_manual(values = custom_colors) + # Set fill colors for confidence intervals
labs(
x = "Jahr",
y = "Stimmenanteil",
title = "Umfragen & Wahlergebnisse [Brandenburg]",
subtitle = "Quelle: wahlrecht.de, @USMortality",
color = "Partei",
fill = "Partei"
) +
theme_minimal() + # A clean theme
theme(
axis.text.x = element_text(angle = 45, hjust = 1),
legend.position = "right"
)
ggplot2::ggsave(
filename = "chart1.png", plot = chart, width = width, height = height,
units = "px", dpi = 72 * sf, device = grDevices::png, type = c("cairo")
)
@USMortality
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment