2

I am generating multiple bar_chart plots in R with ggplot2. I am using grid.arrange to put them all together in one image.

I would like them to have the same width, but my problem is that their legend labels have different length, and thus they influence the width.

Here's a simplified sample of my code (my code actually has a for loop repeated 10 times):

library(ggplot2)
library(gridExtra)

i <- 1
plot_list <- list()

var <- c(0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0)


var2 <- c(0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0)

P_this <- ggplot(data.frame(var), aes(factor("nothing"), fill=factor(var))) + geom_bar(stat="count", position="stack") +  scale_fill_discrete(labels=c("long title one", "long title two"))

plot_list[[length(plot_list) + 1]] <- P_this

P_this2 <- ggplot(data.frame(var2), aes(factor("nothing"), fill=factor(var))) + geom_bar(stat="count", position="stack") +  scale_fill_discrete(labels=c("women", "men"))

plot_list[[length(plot_list) + 1]] <- P_this2

do.call("grid.arrange", c(plot_list, ncol=1))
dev.off()

This code generated this image: enter image description here

Please notice that I have to keep the do.call("grid.arrange", c(plot_list, ncol=1)) command.

How can I force these two barcharts to have the same width? Thanks!

DavideChicco.it
  • 3,318
  • 13
  • 56
  • 84

0 Answers0