Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving constant bar width in ggplot stacked bar graph with different number of bars

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)

like image 487
Hamid Avatar asked Oct 31 '25 22:10

Hamid


1 Answers

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.

like image 198
Duck Avatar answered Nov 03 '25 13:11

Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!