Search code examples
rggplot2bar-chartcategorical-data

How to arrange the bars of the "fill" variable in ggplot together?


This is my code:

sur %>% 
  select(circumstances_bite, circumstances_bite_broad) %>% 
  drop_na() %>% 
  ggplot(aes(y=fct_infreq(circumstances_bite), fill = circumstances_bite_broad))+
  geom_bar()+
  xlab("No of people")+
  ylab("circumstance of bite")+
  ggtitle ("circumstance of bite by a pet dog")

How do I group the bars according to the fill variable? Groping the different colour bars together and not seperately. Both the variables are factors.

my graph


Solution

  • A simple solution would be to compute the counts manually outside of ggplot, then order you data in your desired order, i.e. by circumstances_bite_broad and fix the order via forecast::fct_inorder.

    Using some fake random example data:

    set.seed(123)
    
    library(tidyverse)
    
    sur <- data.frame(
      circumstances_bite = sample(LETTERS[1:26], 100, replace = TRUE)
    ) |>
      mutate(circumstances_bite_broad = case_when(
        circumstances_bite %in% LETTERS[1:9] ~ "a",
        circumstances_bite %in% LETTERS[10:18] ~ "b",
        circumstances_bite %in% LETTERS[19:26] ~ "c"
      ))
    
    sur %>%
      select(circumstances_bite, circumstances_bite_broad) %>%
      drop_na() %>%
      count(circumstances_bite, circumstances_bite_broad) |>
      arrange(circumstances_bite_broad, desc(n)) |>
      mutate(circumstances_bite = fct_inorder(circumstances_bite)) |>
      ggplot(aes(x = n, y = circumstances_bite, fill = circumstances_bite_broad)) +
      geom_col() +
      xlab("No of people") +
      ylab("circumstance of bite") +
      ggtitle("circumstance of bite by a pet dog")
    

    enter image description here