请考虑这个经过修改但无耻窃取的代码:
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)
在这些条件下,图例的放置不像gA$grobs[[8]]
2 个条目那样工作,并且代码显式访问第一个条目以确定所需的图例调整。
因此,我想要做的是遍历所有条目gA$grobs[[8]]
并找到要使用的最大宽度。
顺便提一句:
library(gtable)
a <- gtable(unit(1:3, c("cm")), unit(5, "cm"))
a # See, "TableGrob" exists (somewhat) ;)
我希望这能澄清我打算做的事情。
感谢您的任何指点,乔