3

I want to plot a stacked bar-chart with ggplot2 that have fixed bars' width. The problem is when the number of bars is different across plots, the gridExtra::grid.arrange() or other functions like egg::ggarrange() stretches the plots with a smaller number of bars, and the bin width will change. Is there any way to have the same bin width in all plots? I've checked several other post like this one: The same width of the bars in geom_bar(position = "dodge"), but they didn't help!

NOTE: I'm not using facets due to some reasons in the original code, and I'm using a simplified version of my data. The original data has 50 types and more than 1000 samples.


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

The result of the code (different bin width)

Hamid
  • 41
  • 4

1 Answers1

2

I will leave for your consideration using facet_grid() with two examples. Maybe they can be for your interest:

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)

Output:

enter image description here

And second option:

#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)

Output:

enter image description here

In both examples bar widths are equal.

Duck
  • 39,058
  • 13
  • 42
  • 84
  • Thanks for your answer, Duck! I found another way to use your facet method in my original code, and the problem is solved. But I'll let the question be opened, so if someone finds an answer to my question without using facet, let me know. – Hamid Sep 25 '20 at 07:20