Please consider this modified, but shamelessly filched code:
library(ggplot2)
library(gtable)
library(gridExtra)
p1 <- ggplot(
data.frame(
x=c("a","b","longer"),
y=c("happy","sad","ambivalent about")),
aes(x=factor(0),fill=x)) +
geom_bar() +
geom_point(aes(y=seq(3),color=y))
p2 <- ggplot(
data.frame(
x=c("a","b","c"),
y=c("happy","sad","ambivalent about life")),
aes(x=factor(0),fill=y)) +
geom_bar()
# Get the widths
gA <- ggplot_gtable(ggplot_build(p1))
gB <- ggplot_gtable(ggplot_build(p2))
# The parts that differs in width
leg1 <- with(gA$grobs[[8]], grobs[[1]]$widths[[4]])
leg2 <- with(gB$grobs[[8]], grobs[[1]]$widths[[4]])
# Set the widths
gA$widths <- gB$widths
# Add an empty column of "abs(diff(widths)) mm" width on the right of
# legend box for gA (the smaller legend box)
gA$grobs[[8]] <- gtable_add_cols(gA$grobs[[8]], unit(abs(diff(c(leg1, leg2))), "mm"))
# Arrange the two charts
grid.newpage()
grid.arrange(gA, gB, nrow = 2)
Under these conditions the placement of the legends does not work as wanted as gA$grobs[[8]]
has 2 entries and the code accesses explicitly the first one to determine the needed legend adjustment.
What I accordingly want to do is iterate over all entries in gA$grobs[[8]]
and find the maximal width to use.
BTW:
library(gtable)
a <- gtable(unit(1:3, c("cm")), unit(5, "cm"))
a # See, "TableGrob" exists (somewhat) ;)
I hope this clears up what I intend to do.
Thanks for any pointers, Joh