使用多个分组变量对条形图中的条形进行排序

问题描述 投票:0回答:1

这是 MWE。

df <- data.frame(Y = c(1:12),
                 Combination = c(1,1,2,2,3,3,4,4,5,5,6,6),
                 Treatment = c("AX", "AY", "AY", "AX", 
                               "BZ", "BY", "BZ", "BX", 
                               "BY", "BX", "BX", "BY"),
                 Stage = rep(c(1,2), 6)
                      )

对于此数据,我想创建一个条形图,其中 x 轴按 Combination 分组,条形由 Treatment 填充,并且在每个组合中,我希望条形按 stage 排序。

以下是我的代码,只能实现前两个条件。我搜索了一些解决方案,但它们对于这个特定的数据集效果不佳。

my_greys <- c("#000000", "#707070", "#000000","#707070", "#CCCCCC")

ggplot(test.df, aes(y = Y, fill = factor(Treatment), x = Combination  ) ) +
   geom_bar(position='dodge', stat='summary', fun='mean', show.legend = T) +
   theme_classic() + 
   scale_fill_manual(values = my_greys)

The Bar Chart

我的目的:我希望每个组合中的条形(由治疗填充)按 Stage 变量排序。

r ggplot2 bar-chart
1个回答
0
投票

使用

group
美学,例如像这样:

ggplot(test.df, aes(factor(Combination), Y, fill = factor(Treatment), group = Stage)) +
  geom_bar(position='dodge', stat='summary', fun='mean')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.