Last active
May 11, 2020 19:19
-
-
Save statgeek/8ca9b588ad2ae16e702b071bf258c464 to your computer and use it in GitHub Desktop.
R - ggplot - customize the order of categories on a chart
This file contains hidden or 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
#This shows how to : | |
#1. customize the order of bars in a bar plot | |
#2. format legend | |
#3. Add labels to axis, graph title, legend | |
#4. Create clustered bar chart | |
#F.Khurshed | |
#2020-05-11 | |
#create fake data to play with | |
demo <- dput(structure(list(days_stay = c("<=30", "<=30", "120+", "31 to 60", | |
"31 to 60", "61 to 90", "61 to 90", "91 to 120", "91 to 120"), | |
status = c("AB Status 2", "CD Status 1", "CD Status 1", "AB Status 2", | |
"CD Status 1", "AB Status 2", "CD Status 1", "AB Status 2", | |
"CD Status 1"), pct = c(0.96, 0.64, | |
0.00, 0.02, 0.08, | |
0.02, 0.22, 0.04, | |
0.15)), class = c("rowwise_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, 9L))) | |
#order of categories desired | |
days_order = c("<=30", "31 to 60", "61 to 90", "91 to 120", "120+") | |
status_order = c("CD Status 1", "AB Status 2") | |
#graph applying the order using the factor function with the levels option | |
ggplot(demo, aes(x=factor(days_stay, levels=days_order), y=pct, fill=factor(status, levels=status_order))) + | |
#clustered bar chart | |
geom_bar(stat="identity", position="dodge") + | |
#labels for graph, axis and legend | |
labs(title="Comparison of Stay Duration", x = "Days Stay", y="Frequency", fill="Time Frame") + | |
#format axis as percent | |
scale_y_continuous(labels = scales::percent) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment