I have a ggplot2 plot with both positive and negative geom_bar values. For the geom_bar that shows the negative values, I’m having an issue where the position of geom_text is not displayed correctly. How can I fix this problem?
library(ggplot2)
library(scales)
library(dplyr)
data_schule_schulform <- structure(list(Schuljahr = c("2017", "2018", "2018", "2019",
"2019", "2020", "2021", "2021", "2022", "2023", "2023", "2024",
"2024", "2024"), Herkunftsschulform = c("Gymnasium", "Förderschule",
"Gymnasium", "Förderschule", "Gymnasium", "Gymnasium", "Gesamtschule",
"Gymnasium", "Gymnasium", "Gymnasium", "Sonstiges", "Förderschule",
"Gymnasium", "Sonstiges"), Anzahl = c(7, 2, 2, 1, 6, 2, 1, 2,
4, 1, 57, 1, 8, 44)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -14L))
data_2_schule_schulform <- structure(list(Schuljahr = c("2017", "2018", "2019", "2019",
"2019", "2021", "2022", "2022", "2023", "2023", "2023", "2024",
"2024", "2024", "2024"), Schulform = c("Hauptschule", "Hauptschule",
"Förderschule", "Gymnasium", "Hauptschule", "Hauptschule", "Gymnasium",
"Hauptschule", "Förderschule", "Gesamtschule", "Hauptschule",
"Förderschule", "Gesamtschule", "Gymnasium", "Hauptschule"),
Anzahl = c(3, 1, 1, 1, 5, 3, 1, 4, 1, 1, 2, 1, 1, 1, 9)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -15L))
p1 <- ggplot() +
geom_bar(
data = data_schule_schulform,
aes(fill = Herkunftsschulform, y = Anzahl, x = Schuljahr),
position = 'stack', stat = 'identity') +
geom_text(
data = data_schule_schulform,
aes(
fill = Herkunftsschulform, y = Anzahl, x = Schuljahr,
label = ifelse(
Anzahl >= 3,
comma(Anzahl, accuracy = 1L, big.mark = ".", decimal.mark = ","),
""
)
),
position = position_stack(vjust = 0.5), size = 3, color= "black", fontface= "bold") +
geom_bar(
data = data_2_schule_schulform,
aes(fill = Schulform, y = Anzahl*-1, x = Schuljahr),
position = 'stack', stat = 'identity') +
labs(
title = "xxx",
subtitle = "xxx",
x = "",
y = "",
fill = ""
) +
scale_y_continuous(labels = function(x) format(x, big.mark = ".")) +
theme_minimal() +
theme(
axis.text.x = element_blank(),
axis.text.y = element_text(size = 8)
) +
geom_text(
data = data_2_schule_schulform %>%
filter (Anzahl >= 3),
aes(fill = Schulform, y = Anzahl*-1, x = Schuljahr, label = comma(Anzahl, accuracy = 1L, big.mark = ".", decimal.mark = ",")),
position = position_stack(vjust = 0.5), size = 3, color= "black", fontface= "bold") +
geom_hline(yintercept = 0, color = "white", size = 2) + # Add a horizontal line at y = 0
theme(
plot.margin = margin(b = 10),
legend.position = "none"
) +
guides(
alpha = 'none'
)