( , ) , ( ), . , . , . :
library(gridExtra)
p1 = qplot(data = d[d$variable != "very_long_label_name",], factor(value),
position = "dodge", geom = "histogram", fill = variable)
p2 = qplot(data = d[d$variable != "y",], factor(value), position = "dodge",
geom = "histogram", fill = variable)
, , , :
get_leg = function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
justify <- function(x, hjust="center", vjust="center", draw=TRUE){
w <- sum(x$widths)
h <- sum(x$heights)
xj <- switch(hjust,
center = 0.5,
left = 0.5*w,
right=unit(1,"npc") - 0.5*w)
yj <- switch(vjust,
center = 0.5,
bottom = 0.5*h,
top=unit(1,"npc") - 0.5*h)
x$vp <- viewport(x=xj, y=yj)
if(draw) grid.draw(x)
return(x)
}
:
leg1 = get_leg(p1)
leg2 = get_leg(p2)
w = c(0.6,0.4)
png("test1.png", height = 3, width = 6, units="in", res=100)
grid.arrange(p1 + theme(legend.position="none"),
justify(leg1,"left","center"),
widths=w, ncol=2)
dev.off()
png("test2.png", height = 3, width = 6, units="in", res=100)
grid.arrange(p2 + theme(legend.position="none"),
justify(leg2,"left","center"),
widths=w, ncol=2)
dev.off()


, : y , , - , y- ( ), y . , . :
p3 = ggplot(iris, aes(Sepal.Length, Sepal.Width*1e6, colour=Species)) +
geom_point()
leg3 = get_leg(p3)
gA <- ggplotGrob(p1 + theme(legend.position="none"))
gB <- ggplotGrob(p3 + theme(legend.position="none"))
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)
png("test1a.png", height = 3, width = 6, units="in", res=100)
grid.arrange(gA, justify(leg1,"left","center"),
widths=w, ncol=2)
dev.off()
png("test3.png", height = 3, width = 6, units="in", res=100)
grid.arrange(gB, justify(leg3,"left","center"),
widths=w, ncol=2)
dev.off()
p1, p1 p3, :


