I want to control my font colour using explicitly named colours in the label_col column. However, it seems that the colours "black" and "white" end up being ordered alphabetically by the colour name, instead of following the same fill and position specified in ggplot(aes()) and geom_col().
Here is my minimal example with black and white:
list_order <- c("a", "b", "c", "d", "e", "f")
test <- data.frame(indicator = rep(list_order, 2),
mean = c(1.1, 0.3, 6.3, 4, 7, 2.1, 1.2, 0.7, 6.9, 3.3, 5.4, 1.8),
group = c(rep("Group A", 6), rep("Group B", 6)))
test %>%
mutate(indicator = factor(indicator, levels = list_order),
label = round(mean, 1),
label_col = ifelse(indicator %in% c("a", "d", "e", "f"), "black", "white")) %>%
ggplot(aes(x = group, y = mean, fill = indicator)) +
geom_col(width = 0.7, position = "stack") +
geom_text(aes(label = label, color = label_col), size = 3, position = position_stack(vjust = 0.5)) +
scale_color_identity() +
scale_fill_viridis(discrete = T, option = "plasma")
If I change the colours in label_col to both "white", or both "black", I get them in the correct places like here:
Is there something I am not understanding about how ggplot positions labels and text? I know how to work around this by using scale_color_manual(), but would also like to understand why scale_color_identity() is not working here, and the solution for it.


