R语言 在单个图表中混合使用堆叠条形图和非堆叠条形图

bvk5enib  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(203)

我试图在一个图表中混合使用堆叠和非堆叠条形图。
下面是示例代码:

Indicators <- c("Z","X","C","NO C","NA C","LOW C","HIGH C","D","E","F","G","H","LOW H","MED H","HIGH H",
                "I","LOW I","MED I","HIGH I","J","LOW J","MED J","HIGH J")

Class_1 <- c(0.44,0.01,"",0.6,0.13,0.11,0.16,0.08,0.01,0.14,0.21,"",0.55,
0.23,0.22,"",0.4,0.31,0.29,"",0.41,0.23,0.36)

data <- data.frame(Indicators,Class_1)

我怎样才能制作一个既有非堆叠条形图又有堆叠条形图的图表呢?我真的很感激所有的帮助!谢谢!

k97glaaz

k97glaaz1#

基本上你想要一个堆叠条形图,即使对于某些类别没有什么可堆叠的。为此,你必须做一些数据的处理和清理,比如去掉空值行,并将Indicators列一分为二:

library(dplyr)
library(ggplot2)
library(tidyr)

data1 <- data |> 
  filter(Class_1 != "") |> 
  mutate(Class_1 = as.numeric(Class_1)) |> 
  separate(Indicators, into = c("level", "which"), fill = "left") |> 
  replace_na(list(level = "Total"))

ggplot(data1, aes(which, Class_1, fill = level)) +
  geom_col()

brtdzjyr

brtdzjyr2#

更新II:

library(tidyverse)

my_pattern1 <- c("No|Non|Low-risk|High-risk|Low|Medium|High")

data %>% 
  filter(Class_1 != "") %>% 
  mutate(x = case_when(str_detect(Indicators, 'CSA|childhood sexual abuse') ~ "Childhood sexual abuse",
                       str_detect(Indicators, 'discrimination') ~ "discrimination"),
         y = str_extract(Indicators, my_pattern1)) %>% 
  mutate(z = str_remove_all(Indicators, my_pattern1)) %>% 
  mutate(y= ifelse(is.na(y), "Total", y)) %>% 
  ggplot(aes(x = z, y = as.numeric(Class_1), fill= y))+
  geom_bar(stat = "identity", position = "stack")+
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1))

更新:(@camille是对的,我现在修改了我的答案,删除了第一个)

library(tidyverse)
data %>% 
  separate(Indicators, c("Indicators_1",  "Indicators_2")) %>% 
  mutate(Indicators_3 = ifelse(is.na(Indicators_2), "Total", Indicators_1),
         Indicators_2 = coalesce(Indicators_2, Indicators_1)) %>% 
  filter(Class_1 != "") %>% 
  ggplot(aes(x = Indicators_2, y = as.numeric(Class_1), fill= Indicators_3))+
  geom_bar(stat = "identity", position = "stack")

相关问题