Search code examples
rstacked-bar-chart

X axis edit for stacked histogram


I'm looking to sort a stacked graph as demonstrated here: How to plot multiple stacked histograms together in R?

However I need the x axis not to be 'value' with numbers, but instead have groups like 'car' 'van' 'bike', with the stacked plots occuring for each group. I'm not great at R yet and I can't work out how to edit it to do what I need. Explanations to solutions so I can learn and improve would also be really appreciated. Thanks

example input:
enter image description here

Output plot would have 'car', 'van', 'bike' on the x axis, 'count' on y axis, the stack on each group being made up of the 'red', 'blue', 'yellow' counts

I think I may have found the answer here:https://r-charts.com/part-whole/stacked-bar-graph/

If no ones solves it before I've had a go at the above link I may sort an answer myself, will see how things go.


Solution

  • Assuming that the last row of your dataset actually refers to the name of the column, you may need to lengthen your data.

    library(tidyverse)
    
    df <- data.frame(
      "color" = c("red", "blue", "yellow"),
      "car" = c(6,2,2),
      "van" = c(1,4,4),
      "bike" = c(8,1,1)) %>%
      pivot_longer(cols = -color,
                   names_to = "name",
                   values_to = "value")
    
    ggplot(df, aes(x = name, y = value, fill = color)) +  
      geom_bar(position = "stack", stat = "identity") 
    

    enter image description here