I'm trying to add labels to a stacked bar chart but when I try to change the colors of the text, the numbers move around. First code example works - numbers are where they are expected but once I add color, things move around.
library(tidyverse)
library(viridis)
#> Loading required package: viridisLite
slide6dat <- tibble(
mode=c(rep("Phone", 5), rep("Web", 5)),
resp=rep(c("Nearly every day", "More than half the days", "Several days", "Not at all", "DK/REF"), 2),
value=c(10, 9, 18, 61, 2, 10, 9, 31, 50, 0),
fontcolor=rep(c("white", "white", "black", "black", "black"), 2)
) %>%
mutate(resp=factor(resp, levels=c("Nearly every day", "More than half the days", "Several days", "Not at all", "DK/REF")))
slide6dat %>%
mutate(vallab=str_c(round(value), "%")) %>%
ggplot(aes(fill=resp, y=value, x=mode)) +
geom_bar(position=position_stack(reverse=TRUE), stat="identity") +
geom_text(aes(label=vallab), position = position_stack(vjust=0.5, reverse = TRUE), size=5) +
scale_fill_viridis_d(option="plasma")+
coord_flip()
slide6dat %>%
mutate(vallab=str_c(round(value), "%")) %>%
ggplot(aes(fill=resp, y=value, x=mode)) +
geom_bar(position=position_stack(reverse=TRUE), stat="identity") +
geom_text(aes(label=vallab, color=fontcolor), position = position_stack(vjust=0.5, reverse = TRUE), size=5) +
scale_fill_viridis_d(option="plasma")+
scale_color_identity() +
coord_flip()
Created on 2022-04-20 by the reprex package (v2.0.1)