How does one change the color of the text in ggplot? For example, I have a stacked bar plot. I want to make the labels black when the background is light blue or green.
Here is a meaningless dummy sample:
library(dplyr)
library(ggplot2)
df <- mpg %>%
mutate(cyl = as.character(cyl)) %>%
group_by(model, cyl) %>%
summarize(hwy = mean(hwy), .groups = "keep") %>%
ungroup() %>%
group_by(model) %>%
mutate(hwy = round(hwy / sum(hwy), 2)) %>%
ungroup() %>%
head(11) %>%
mutate(color = case_when(cyl == "4" ~ "white",
cyl == "6" ~ "black",
cyl == "8" ~ "black"))
df %>%
ggplot(data = ., aes(x = model, y = hwy, fill = cyl, label = hwy)) +
geom_bar(stat = "identity", position = "fill") +
geom_text(color = "white", position = position_stack(vjust = 0.5)) +
scale_fill_manual(values = c("dark blue", "light blue", "green"),
name = "cyl",
breaks = c("4", "6", "8"),
labels = c("4", "6", "8"))
I tried using scale_color_manual
, as in this example (More than 1 color in geom_text()) but it didn't work. The solution in this example didn't even work for me on the sample in the question itself. Maybe because it's 8 years old, idk.
Either a solution that chooses colors dynamically in the ggplot
call based on the fill color or one that maps the "color" variable to text colors would work.