在 ggplot2()/geom_col 中,如何更改堆叠条矩形序列和填充颜色

in ggplot2()/geom_col, how to change stack bar retangular sequence and fill color

在下图中,1) 如何将类别 'A' 对齐到 x 轴(y 轴从 0 开始)?
2) 如何更改 sub_category 填充颜色?想要更改为 'pink'(颜色与类别颜色相似)。有人可以帮忙吗?

library(tidyverse)
plot_data <- data.frame(category=c('A','A','B','C'),
           sub_category=c('a1','a2','b1','c1'),
           value=c(6,12,3,2))

plot_data %>% mutate(sub_category=if_else(category=='A',
                                          sub_category,category)) %>% 
  pivot_longer(names_to = 'title',values_to ='cat_region',-value) %>% 
  filter(!(title=='sub_category'&cat_region %in% c('B','C') )) %>% 
  group_by(title,cat_region) %>% 
  summarise(value_sum=sum(value)) %>% 
  ggplot(aes(x=title,y=value_sum,fill=cat_region,
             group=interaction(title,cat_region)))+geom_col()

我认为您正在寻找 scale_fill_manual 到 select 填充颜色,以及 position_stack(reverse = TRUE) 来反转堆叠顺序:

plot_data %>% 
  mutate(sub_category = if_else(category=='A', sub_category, category)) %>% 
  pivot_longer(names_to = 'title', values_to = 'cat_region', -value) %>% 
  filter(!(title == 'sub_category' & cat_region %in% c('B','C'))) %>% 
  group_by(title, cat_region) %>% 
  summarise(value_sum = sum(value)) %>% 
  ggplot(aes(x = title, y = value_sum, fill = cat_region,
             group = interaction(title,cat_region))) +
  geom_col(position = position_stack(reverse = TRUE)) +
  scale_fill_manual(values = c(A = "#f8766d", a1 = "#ffa8a3",
                               a2 = "#ffe2e0", B = "#00b0f6",
                                C = "#74d67f")) +
  theme_bw()