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

Visualizing multiple dummy variables in a proportional stacked bar

I have ten dummy variables [Yes/No]. I can’t convert them to one categorical variable as people in this survey can tick yes on more than one of these dummies.

I need to represent the percentage of yes answers for all these variables in one stacked bar graph. The below is my attempt but no idea how to even get a single variable represented (keep getting error that x needs to be defnied) not to mention multiple.

I’ve picked the stacked bar graph idea from https://r-graphics.org/recipe-bar-graph-proportional-stacked-bar

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

Any help would be appreciated.


a <- c("yes", "yes", "no", "no", "yes", "no", "yes", "no", "no", "no")
b <- c("yes", "no", "no", "no", "yes", "no", "no", "yes", "no", "yes")
c <- c("yes", "no", "yes", "no", "yes", "yes", "no", "yes", "yes", "no")

test <- data.frame(a, b, c)

ggplot(test, aes(y = a)) + 
  geom_col(position = "fill")

https://r-graphics.org/recipe-bar-graph-proportional-stacked-bar

>Solution :

The solution is to reshape the data to long format and to use geom_bar instead.
In the code below I will use the pipe operator introduced in R 4.1.0 and a function from package tidyr to reshape the data.

library(ggplot2)

test |>
  tidyr::pivot_longer(a:c) |>
  ggplot(aes(x = name, fill = value)) + 
  geom_bar(position = "fill")

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