How to make a percent stacked barplot of interactions with ggplot?

137 Views Asked by At

Let's say our data frame is mtcars[, c("vs", "am")]. I want a percent stacked barplot/barchart with 2 columns, one for vs and other for am, each one with 2 groups, ==1 and ==0, but splitted in such a way that looking at the 2 columns I would observe 4 groups. Let's see:

library(dplyr)
mtcars %>% select(vs, am) %>% sjmisc::frq(interaction(vs,am))
interaction(vs, am) <categorical>
# total N=32  valid N=32  mean=0.48  sd=0.51

Value |  N | Raw % | Valid % | Cum. %
-------------------------------------
 0.00 | 12 | 37.50 |   37.50 |  37.50
 0.10 |  6 | 18.75 |   18.75 |  78.12
 1.00 |  7 | 21.88 |   21.88 |  59.38
 1.10 |  7 | 21.88 |   21.88 | 100.00
 <NA> |  0 |  0.00 |    <NA> |   <NA>

There would be an horizontal section in which the group would be 1 for both columns and it would correspond to 21.88%. Another horizontal section in which vs==1 but am==0 would be another 21.88%. There would be a third section corresponding to 18.75%, where vs==0 and am==1 and a last horizontal section where the group in both columns would be 0, and the percentage of 37.5 %. In the y axis would be indicated the cumulative N or the cumulative %.

Is it some way with ggplot or any extension (maybe like ggmosaic or ComplexUpset)?

Thank you!

PS: The question comes from the function stablelearner::image, but it is implemented with base R and I do not know how to translate it.

0

There are 0 best solutions below