Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading