Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have different geom_text() labels in a faceted, stacked bar graph in R with ggplot?

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!

like image 419
Giselle Sleapy Avatar asked Oct 23 '25 02:10

Giselle Sleapy


1 Answers

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

like image 113
StupidWolf Avatar answered Oct 24 '25 19:10

StupidWolf