4

I am trying to use facet_wrap with stacked bar graphs, and I'd like to have labels on the bars showing the value of each part of the bar.

Using the diamonds dataset as an example:

My geom_text code works fine when there is only one graph, albeit cramped for the shorter bars:

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
geom_text(data = . %>% 
          group_by(cut, clarity) %>%
          tally() %>%
          ungroup() %>% 
          group_by(cut) %>%
          ungroup(),
        aes(y = n, label = n),
        position = position_stack(0.5),
        show.legend = FALSE) 

Labeled bar plot without faceting

However, when I add the faceting, all the labels display in all the individual facets:

diamonds %>%
  ggplot(aes(x = cut, fill = clarity)) +
  geom_bar() +
  facet_wrap(~ color) +
  geom_text(data = . %>% 
              group_by(cut, clarity) %>%
              tally() %>%
              ungroup() %>% 
              group_by(cut) %>%
              ungroup(),
            aes(y = n, label = n),
            position = position_stack(0.5),
            show.legend = FALSE)

Faceted bar plot with replicated labeling

How can I make it so that the labels only show up on the relevant bars?

Thanks!

2 Answers2

3

I think you need to include color in the group_by + tally so that it can be assigned to the correct facet:

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color,scale="free_y") +
geom_text(data = . %>% 
          count(cut, clarity,color),
            aes(y = n, label = n),size=1,
            position = position_stack(0.5),
            show.legend = FALSE)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
3

Personally, I find the ..count.. special variable to be easier to work with.

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
  geom_bar() +
  facet_wrap(~ color,scale="free_y") +
  stat_count(geom = "text", 
             aes(y =..count.., label = ..count..),
             position=position_stack(0.5), size = 2)

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57