Search code examples
rggplot2forcats

Stacked bar chart: How to arrange the groups with forcats package


I am working a making som nice plots that I can copy-paste when needed (that is why I have included so many options). So I have this plot:

library(tidyverse)
    mtcars %>% 
      group_by(cyl) %>% 
      summarise(n=n()) %>% 
      ungroup() %>% 
      mutate(cars = "cars") %>% 
      ggplot(aes(x = as.factor(cars), y = n, fill=as.factor(cyl))) +
      geom_bar(stat="identity", width = .3) +
      geom_text(aes(label = paste0(round(n, digits = 0), "stk.")),
                position = position_stack(vjust = 0.5)) +
      labs(title = "Number of cars with cylinders in the data set", 
           subtitle= "If needed",
           caption= "Fodnote",
           x= "", y="Antal",
           fill="# of cylinders") +
      theme(#legend.position="none",
            plot.caption = element_text(hjust = 0))

enter image description here

How can I reorder the stacks so e.g. the blue is at the bottom, then the red stack and the green stack on top. Thanks. I think the solution involes forcats...


Solution

  • Is this what you're looking for? To change the fill color, use scale_fill_manual() or scale_fill_brewer()

    library(tidyverse)
    library(forcats)
    
    mtcars %>% 
      group_by(cyl) %>% 
      summarise(n=n()) %>% 
      ungroup() %>% 
      mutate(cars = "cars",
             cars = factor(cars),
             cyl  = factor(cyl)) %>% 
    
      # use fct_reorder here
      mutate(cyl = fct_reorder(cyl, n)) %>% 
    
      ggplot(aes(x = cars, y = n, fill = cyl)) +
      geom_col(width = .3) +
      geom_text(aes(label = paste0(round(n, digits = 0), "stk.")),
                position = position_stack(vjust = 0.5)) +
      labs(title = "Number of cars with cylinders in the data set", 
           subtitle = "If needed",
           caption = "Footnote",
           x = "", y = "Antal",
           fill = "# of cylinders") +
      theme(#legend.position="none",
        plot.caption = element_text(hjust = 0))