improve bar plot fraktionen helper

This commit is contained in:
2021-08-03 11:33:24 +02:00
parent 354d18050b
commit e2caf1ff4e
2 changed files with 55 additions and 17 deletions
+42 -7
View File
@@ -20,20 +20,55 @@ party_colors <- c(
SPD="#DF0B25",
"BÜNDNIS 90 / DIE GRÜNEN"="#4A932B",
"DIE LINKE"="#BC3475",
"AfD&Fraktionslos"="#1A9FDD",
Fraktionslos="#FEEB34"
"AfD&Fraktionslos"="#AAAAFF",
Fraktionslos="#AAAAAA"
)
party_order <- factor(c("Fraktionslos", "AfD&Fraktionslos",
"DIE LINKE", "BÜNDNIS 90 / DIE GRÜNEN", "SPD", "CDU/CSU",
"FDP", "AfD", NA_character_))
#' @export
bar_plot_fraktionen <- function(tb, variable, fill, title=NULL, xlab = "Fraction",
ylab="n", filllab="Fraction") {
ggplot(tb, aes(x = reorder(fraktion, -{{variable}}), y = {{variable}}, fill = {{fill}})) +
scale_fill_manual(values = party_colors) +
bar_plot_fraktionen <- function(tb,
x_variable = NULL, # default is fraktion
y_variable = NULL, # default is n
fill = NULL, # default is fraktion
title = NULL,
xlab = "Fraction",
ylab = "n",
filllab = "Fraction",
flipped = TRUE,
position = "dodge",
reorder = FALSE) {
# capture expressions in arguments
fill <- enexpr(fill)
y_variable <- enexpr(y_variable)
x_variable <- enexpr(x_variable)
# set default values
if (is.null(fill)) fill <- expr(fraktion)
if (is.null(y_variable)) y_variable <- expr(n)
if (is.null(x_variable)) x_variable <- expr(fraktion)
# either reorder fraction factor by variable value
if (reorder) maps <- aes(x = reorder(!!x_variable, -!!y_variable),
y = !!y_variable,
fill = reorder(!!fill, -!!y_variable))
# or reorder fraction factor by party seat order in parliament (default)
else maps <- aes(x = factor(!!x_variable, levels = party_order),
y = !!y_variable,
fill = factor(!!fill, levels = party_order))
# make a bar plot
ggplot(tb, maps) +
scale_fill_manual(values = party_colors, na.value = "#555555") +
xlab(xlab) +
ylab(ylab) +
labs(fill = filllab) +
ggtitle(title) +
geom_bar(stat = "identity") + coord_flip()
geom_bar(stat = "identity", position = position) ->
plt
# if flipped == TRUE, draw bars horizontally (default TRUE)
if (flipped) plt + coord_flip() else plt
}
# Counts how many talks do match a given pattern and summarises by date