Created
January 24, 2017 03:18
-
-
Save rblissett/c8db38b15c50b1e7a32103a974955734 to your computer and use it in GitHub Desktop.
Function to create stacked bar graph of a set of variables with the same categorical scale (e.g., survey responses in a question set)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get ranking graph for multiple choice | |
getmcgraph <- function(t, levels, items, sortby) { | |
t <- lapply(t, function(x) factor(x, levels=levels)) | |
end <- data.frame(matrix(NA, nrow=1, ncol=length(levels))) | |
names(end) <- levels | |
for(i in 1:length(t)) { | |
end <- rbind(end, round(100*prop.table(table(t[i])), digits=2)) | |
} | |
end <- end[-1,] | |
end <- cbind(items, end) | |
names(end)[1] <- "Item" | |
end <- end[order(end[sortby]),] | |
itemorder <- as.character(end[["Item"]]) | |
library(reshape) | |
coldata <- melt(end, id="Item") | |
coldata$Item <- wrap_strings(as.character(coldata$Item), 30) | |
coldata$Item <- factor(coldata$Item, levels=wrap_strings(itemorder, 30), ordered=TRUE) | |
return(ggplot(coldata, aes(x=factor(Item), y=value, fill=factor(variable))) + | |
geom_bar(stat="identity") + | |
xlab("") + | |
ylab("Percent") + | |
coord_flip() + | |
theme + | |
scale_fill_discrete(name="Response")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment