I am trying to reorder my stacked bar plot so that it is from the bottom to top: Epidural, Subdural, Subarachnoid, Intracerebral, and Unspecified. I have included my plot, dataframe, and code below
This is my code:
ggplot(cat, aes(x = headbleed_trauma_primary, y = perc, fill = headbleed_category_primary))+
geom_bar(stat = "identity", position = "stack") +
theme_classic()
This is my data:
structure(list(headbleed_trauma_primary = c("Nontraumatic", "Nontraumatic",
"Nontraumatic", "Nontraumatic", "Nontraumatic", "Traumatic",
"Traumatic", "Traumatic"), headbleed_category_primary = c("Epidural",
"Intracerebral", "Subarachnoid", "Subdural", "Unspecified", "Epidural",
"Subarachnoid", "Subdural"), n = c(15L, 2848L, 1113L, 1295L,
589L, 141L, 2078L, 3477L), perc = c(0.129802699896158, 24.6452059536172,
9.63136033229491, 11.2062997577016, 5.0969193492558, 1.22014537902388,
17.9820006922811, 30.0882658359294)), row.names = c(NA, -8L), class = "data.frame")
You could create a factor
variable and apply ggplot
:
library(dplyr)
library(ggplot2)
cat %>%
mutate(headbleed_category_primary =
factor(
headbleed_category_primary,
levels = c("Epidural", "Subdural", "Subarachnoid", "Intracerebral", "Unspecified")
)
) %>%
ggplot(aes(x = headbleed_trauma_primary, y = perc, fill = headbleed_category_primary))+
geom_bar(stat = "identity", position = "stack") +
theme_classic()
This returns