R语言 手动重新排序堆积条形图[重复]

2uluyalo  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(179)
    • 此问题在此处已有答案**:

How to control ordering of stacked bar chart using identity on ggplot2(6个答案)
昨天关门了。
我正在尝试重新排序我的堆叠条形图,以便它是从下到上:硬膜外,硬膜下,蛛网膜下,脑内,和未指定。我已经包括我的图, Dataframe ,和下面的代码

这是我的代码:

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")
rhfm7lfc

rhfm7lfc1#

您可以创建一个factor变量并应用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()

这将返回

相关问题