'Present multiple dichoctomised variables in horizontal stacked bar chart
Solution 1:[1]
Assuming you have data like this,
head(dat, 3)
# V1 V2 V3 V4 V5 V6 V7 V8 V9
# 1 1 0 1 0 0 1 0 0 0
# 2 1 1 0 0 0 1 0 1 0
# 3 0 1 1 0 1 1 1 1 1
you easily could preprocess the data by using columns frequencies (colSums) and their inverse (subtracting from nrow). Next calculate proportions. Finally put it in barplot and apply some cosmetics.
## preprocess data
cs <- colSums(dat)
pdat <- proportions(rbind(nrow(dat) - cs, cs), margin=2)
# pdat <- rbind(nrow(dat) - cs, cs) ## calculating N instead
## plot and output as .png
png('fooplot.png', 600, 400) ## start .png device
op <- par(mar=c(5, 16, 5, 3)+.1) ## set pars
b <- barplot(pdat, horiz=T, col=c(4, 2), names.arg=rep('', length(cs)),
main='Some title', legend.text=c('yes', 'no'), ,
args.legend=list(x=.2, y=-1.5, bt='n', xpd=TRUE, horiz=T))
text(pdat[1, ]/2, b, paste0(pdat[1, ]*100, '%'), cex=.9)
text(pdat[1, ] + pdat[2, ]/2, b, paste0(pdat[2, ]*100, '%'), cex=.9)
# text(pdat[1, ]/2, b, pdat[1, ], cex=.9) ## if calculating N
# text(pdat[1, ] + pdat[2, ]/2, b, pdat[2, ], cex=.9) ## "
text(-.03, b, q, xpd=TRUE, adj=1)
par(op) ## restore pars
dev.off() ## stop .png device
Find the plot in your working directory getwd().
Data:
set.seed(42)
dat <- sapply(c(.3, .53, .29, .35, .39, .52, .31, .65, .68), \(x) rbinom(100, 1, x)) |>
as.data.frame()
q <- c('Lorem ipsum dolor sit amet?', 'Consectetur adipiscing elit?',
'Sed do eiusmod tempor incididunt?', 'Ut labore et dolore magna aliqua?',
'Donec et odio pellentesque diam?', 'Volutpat commodo sed. Quis risus?',
'Sed vulputate odio ut enim blandit?', 'Malesuada bibendum arcu vitae?',
'Elementum curabitur?')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


