Home > other >  Changing the axis labels in a group of stacked bar charts
Changing the axis labels in a group of stacked bar charts

Time:10-26

I have the following code

library(tibble)
library(tidyr)
library(dplyr)
library(ggplot2)

test <- tibble(
  cat1 = c(rep('foo',6),rep('bar',6)),
  cat2 = rep(c('g1','g2','g3','g4','g5','g6'), 2),
  zoom = rnorm(12, 0, 10),
  zaps = rnorm(12, 5, 10),
  buzz = rnorm(12, -5, 10)
) %>% pivot_longer(c(zoom,zaps,buzz),names_to = 'cat3', values_to='value')

test2 <- inner_join(test, summarise(group_by(test, cat1, cat2), agg = sum(value)))

ggplot(test2, aes(x = cat1, y = value, fill = cat3, label = as.integer(value)))  
  geom_bar(stat = 'identity', position = 'stack')  
  geom_text(position = position_stack(vjust = 0.5), size = 3, color = "#555555")  
  geom_errorbar(aes(ymin = agg, ymax = agg))  
  facet_grid(~ cat2)

which produces the following chart: enter image description here

I like this and I am mostly happy with it, but I would love to include a sum total label for each column (the same value as the horizontal black line) somewhere in the column, ideally either at the bottom above/below the x axis labels or above the top edge of the plot below the g1,g2... Can I do this by changing the displayed labels soo foo in g1 would be 'foo\n8' ? or is there a generic way to tell ggplot to put a number above the bar/foo labels in the plot or above the top edge of the top column component?

CodePudding user response:

You may try this way. Please let me know if I miss something or I'm wrong with your purpose.

df2 %>% 
  group_by(cat1, cat2) %>%
  mutate(n = sum(as.integer(value))) %>%
  rowwise %>%
  mutate(cat1 = paste0(c(cat1, n), collapse = "\n")) %>%
  ggplot(aes(x = cat1, y = value, fill = cat3, label = as.integer(value)))  
  geom_bar(stat = 'identity', position = 'stack')  
  geom_text(position = position_stack(vjust = 0.5), size = 3, color = "#555555")  
  geom_errorbar(aes(ymin = agg, ymax = agg))  
  facet_wrap(~ cat2, scales = "free_x", ncol = 6) 

enter image description here

  • Related