Skip to content

Instantly share code, notes, and snippets.

@rblissett
Created January 24, 2017 03:18
Show Gist options
  • Save rblissett/c8db38b15c50b1e7a32103a974955734 to your computer and use it in GitHub Desktop.
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)
# 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