首页 > 解决方案 > 在具有不同条数的ggplot堆叠条形图中保持恒定条形宽度

问题描述

我想绘制一个ggplot2具有固定条形宽度的堆叠条形图。问题是,当图的条数不同时,gridExtra::grid.arrange()或其他函数(例如egg::ggarrange()用较少的条数拉伸图),并且 bin 宽度会发生变化。有没有办法在所有地块中具有相同的 bin 宽度?我已经检查了其他几篇类似这样的帖子:geom_bar(position = "dodge") 中条形的宽度相同,但它们没有帮助!

注意:由于原始代码中的某些原因,我没有使用构面,并且我使用的是数据的简化版本。原始数据有50种类型和1000多个样本。


new <- data.frame(variable = rep(c('p 1', 'p 2', 'p 3'), 12+4+3),
                  value = sample(1:100, 3*12+3*4+3*3),
                  type = c(rep("A", 3*12), rep("B", 3*4), rep("C", 3*3)), 
                  sample = rep(letters[1:(12+4+3)], each = 3))

my_plot <- function(my_type){
  
  df <- subset(new, new$type %in% my_type)
  gg <- ggplot(df) + 
    aes(group = 1)+
    geom_bar(aes(colour = variable, fill = variable, y = value,
                 x = sample), 
             position="stack", stat="identity",  width=.7) +
    theme_classic() + theme(legend.position = 'None')
  gg
}

p <- lapply(sort(unique(new$type)), my_plot)
g <- do.call(grid.arrange, c(p, ncol = 1))

代码的结果(不同的bin宽度)

标签: rggplot2bar-chart

解决方案


我将使用facet_grid()两个示例供您考虑。也许他们可以满足您的兴趣:

library(ggplot2)
#Code 1
ggplot(new,aes(colour = variable, fill = variable, y = value,
               x = sample)) + 
  geom_bar(position="stack", stat="identity",  width=.7) +
  theme_classic() + theme(legend.position = 'None')+
  facet_grid(.~type,scales = 'free',space = 'free',drop = F)

输出:

在此处输入图像描述

第二个选项:

#Code 2
ggplot(new,aes(colour = variable, fill = variable, y = value,
               x = sample)) + 
  geom_bar(position="stack", stat="identity",  width=.7) +
  theme_classic() + theme(legend.position = 'None')+
  coord_flip()+
  facet_grid(.~type,scales = 'free',space = 'free',drop = F)

输出:

在此处输入图像描述

在这两个示例中,条形宽度相等。


推荐阅读