如何手动指定ggplot堆叠条形图的堆叠顺序(从下到上)
调整ggplot堆叠条形图的堆叠顺序
需求
将堆叠条形图的堆叠顺序从下到上设置为:Epidural、Subdural、Subarachnoid、Intracerebral、Unspecified
当前代码
ggplot(cat, aes(x = headbleed_trauma_primary, y = perc, fill = headbleed_category_primary))+ geom_bar(stat = "identity", position = "stack") + theme_classic()
当前数据框
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")
解决方案
ggplot的堆叠顺序由填充变量的因子水平顺序决定,默认从下到上对应因子levels的顺序。只需将headbleed_category_primary转换为指定顺序的因子即可:
- 转换因子顺序:
cat$headbleed_category_primary <- factor(cat$headbleed_category_primary, levels = c("Epidural", "Subdural", "Subarachnoid", "Intracerebral", "Unspecified"))
- 运行原绘图代码,即可得到符合要求的堆叠顺序。
完整代码如下:
# 转换因子顺序 cat$headbleed_category_primary <- factor(cat$headbleed_category_primary, levels = c("Epidural", "Subdural", "Subarachnoid", "Intracerebral", "Unspecified")) # 绘制堆叠条形图 ggplot(cat, aes(x = headbleed_trauma_primary, y = perc, fill = headbleed_category_primary))+ geom_bar(stat = "identity", position = "stack") + theme_classic()
内容的提问来源于stack exchange,提问作者ltong
相关产品推荐
相关产品推荐

