I have a set of barplots that I am trying to fit into one figure. They have different number of bars in multiple plots and I don't see a way to align them with facet_grid
. Instead I used gtable
for the layout but that complicates matters. I cannot figure out how to correctly aligning the ticks on the x-axis and the enforcing the same width of the bars.
I used the excellent trick from babtiste here to align the width of the y-axis. The placement of the plots was determined by trial and error.
The answers suggested here only seems to work if the plots within the facets are balanced. Using scale_x_discrete(expand = c(0,0))
only seems to affect the top left plot and makes the problem worse.
Below is code to reproduce the problem. Note the difference in width of the bars and the slight misplacement of "2" and "5" between the rows in column 1.
In the real data there are multiple groups in each plot. Using gtable is not a requirement, whatever will align it is good with me.
library(grid)
library(ggplot2)
library(gtable)
dfTestData <- data.frame(yval = c(5, 7, 8, 7, 9, 6, 5),
type = c("T1", "T1", "T2", "T1", "T3", "T1", "T2"),
pos = factor(c(1, 2, 1, 1, 2, 1, 1)),
condition = c("a", "a", "a", "b", "b", "c", "d")
)
dfTestData <- split(dfTestData, dfTestData$condition)
p <- ggplot(data.frame(), aes(pos, yval)) +
geom_bar(stat = "identity") +
facet_grid(~ type, scales = "free_x", space = "free_x")
plots <- lapply(dfTestData, function(x) p %+% x)
plots <- lapply(plots, ggplotGrob)
maxWidth <- grid::unit.pmax(plots$a$widths[2:3],
plots$b$widths[2:3],
plots$c$widths[2:3],
plots$d$widths[2:3]
)
plots$a$widths[2:3] <- as.list(maxWidth)
plots$b$widths[2:3] <- as.list(maxWidth)
plots$c$widths[2:3] <- as.list(maxWidth)
plots$d$widths[2:3] <- as.list(maxWidth)
gt <- gtable(widths=unit(rep(1, 1000), "null"),
heights=unit(c(1,0.2,1), "null"))
gt2 <- gtable_add_grob(gt, plots,
l=c(5,5,655,655),
r=c(605,438,890,890),
t=c(1,3,1,3),
b=c(1,3,1,3))
grid.newpage()
grid.draw(gt2)