Search code examples
rggplot2geom-col

How do I create a stacked column chart ranked by the sum of the elements in the stacked column (in R)?


Problem:

How to get a stacked column chart in R where the x axis is ordered by the sum of the stacked elements?

  • Figure 1: Shows stacking
  • Figure 2: Show ranking by sum

Not really sure how to combine these.

library(tidyverse)

df <- data.frame(
  Name = c("A", "B", "C", "D"),
  Input1 = c(5, 15, 10, 5),
  Input2 = c(20, 15, 5, 15)
)

df1 <- pivot_longer(df, 
                    cols = c("Input1", "Input2"),
                    names_to = "Combined",
                    values_to = "Variable")

#stacks based on individual components

df1 %>%
  ggplot(aes(
    x=Name,
    y=Variable,
    fill = Combined
  )) +
  geom_col(position = 'stack')

#rank orders based on totals

df$Total <- rowSums(df[,c("Input1", "Input2")])
df %>%
  ggplot(aes(
    x=fct_rev(fct_reorder(Name, Total)), 
    y= Total ))+
  geom_col()

enter image description here

I am trying to generate code that takes a data frame and create a stacked column graphic in which the elements on the x-axis are ordered (descending) based on the sum of the stacked elements. I was able to get either a stacked column chart OR an ranked (by sum of components) chart, but not both.


Solution

  • You can use reorder or forcats::fct_reorder to order the x variable based on the sum of the y variable like so:

    library(tidyverse)
    
    df1 %>%
      ggplot(aes(
        x = reorder(Name, Variable, FUN = sum, decreasing = TRUE),
        y = Variable,
        fill = Combined
      )) +
      geom_col(position = "stack")