Add one piece of text next to each stacked bar (ggplot)

Viewed 21

(I have edited the question with a min reproducible code!)

I have a 100% stacked bar chart (horizontal) and would like to put numbers (means) as text next to each of the bars, on the right.

This is the graph I have right now:

graph_data = mpg %>% 
  group_by(manufacturer, class) %>% 
  summarise(
    count = n()
  ) %>% 
  left_join(
    data %>% 
      group_by(manufacturer) %>% 
      summarise(
        manufacturer_total = n()
      )
  )

graph_data %>% 
  ggplot(aes(x = manufacturer, y = count/manufacturer_total, fill = class)) +
  geom_bar(position = 'stack', stat = 'identity') +
  coord_flip()

enter image description here

And I want to be able to put the means in this table, next to the corresponding bar:

hwy_mean = mpg %>% 
  group_by(manufacturer) %>% 
  summarise(
    mean_hwy = round(mean(hwy), digits = 2)
  )

manufacturer mean_hwy
  <chr>           <dbl>
1 audi             26.4
2 chevrolet        21.9
3 dodge            18.0
4 ford             19.4
5 honda            32.6
6 hyundai          26.9

E.g. There would be the text '26.44' next to the audi bar.

I've tried setting hwy_mean as the label and use geom_text but does not work because "Aesthetics must be either length 1 or the same as the data (32): "

1 Answers

I've this rewrite:

graph_data = mpg %>%
  group_by(manufacturer, class) %>%
  summarise(count = n()) %>%
  left_join(mpg %>%
              group_by(manufacturer) %>%
              summarise(manufacturer_total = n()))

graph_data %>%
  ggplot(aes(
    y = manufacturer,
    x = count / manufacturer_total,
    fill = class
  )) +
  geom_bar(position = 'stack', stat = 'identity') ->
  pl_a

hwy_mean = mpg %>% 
  group_by(manufacturer) %>% 
  summarise(
    class = NA,
    mean_hwy = round(mean(hwy), digits = 2)
  )
pl_a +
  geom_text(data = hwy_mean, aes(label = mean_hwy, y = manufacturer, x = .99),
            hjust = 1)

hwy_mean

enter image description here

Related