Labeling stacked bar charts shifts when adding color to text

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)

Hi there, I think converting your fontcolor variable to a factor as well should get what you want:

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")),
         fontcolor=factor(fontcolor, levels = c("white", "black")))

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() 

Thanks! This works but no idea why.

Neither do I! I just figured matching up the variable classes was worth a shot.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.