Remove whitespace between margins when using grid graphics

1,400 views
Skip to first unread message

scott_chamberlain

unread,
May 11, 2011, 1:08:50 PM5/11/11
to ggplot2
Hello,


I have seen some tips on how to adjust margins of ggplot graphics
(plot.margin in opts), but is there a way to simply remove whitespace
between plots?

Consider the following example:

require(ggplot2)

a <- qplot(a, b, data = data.frame(a=rnorm(20), b=rnorm(20)), geom =
"point") +
opts(axis.text.x = theme_blank()) +
labs(x="")
b <- qplot(a, b, data = data.frame(a=rnorm(20), b=rnorm(20)), geom =
"point")

pdf("plot.pdf")
grid.newpage()
pushViewport(viewport(layout = grid.layout(2,2)))
vplayout <- function(x, y)
viewport(layout.pos.row = x, layout.pos.col = y)
print(a, vp = vplayout(1, 1))
print(b, vp = vplayout(2, 1))
print(a, vp = vplayout(1, 2))
print(b, vp = vplayout(2, 2))
dev.off()



I want to easily remove most of the whitespace between the upper two
plots and the lower two plots (or between left and right hand plots)
without having to adjust margins of all the plots using plot.margin).

Thanks! Scott

Dennis Murphy

unread,
May 11, 2011, 2:42:31 PM5/11/11
to scott_chamberlain, ggplot2
Hi:

Here's one way, playing around with the positions of viewports in
grid. I also stripped out the plot.background().

a <- qplot(a, b, data = data.frame(a=rnorm(20), b=rnorm(20)),
geom = "point") +

opts(axis.text.x = theme_blank(), plot.background = theme_blank()) +


labs(x="")
b <- qplot(a, b, data = data.frame(a=rnorm(20), b=rnorm(20)),

geom = "point") + opts(plot.background = theme_blank())

vp1 <- viewport(width = 0.54, height = 0.54, x = 0.27, y = 0.27)
vp2 <- viewport(width = 0.54, height = 0.54, x = 0.27, y = 0.75)
vp3 <- viewport(width = 0.54, height = 0.54, x = 0.76, y = 0.26)
vp4 <- viewport(width = 0.54, height = 0.54, x = 0.76, y = 0.75)

grid.newpage()
pushViewport(viewport(layout = grid.layout(2,2)))
print(b, vp = vp1)
print(a, vp = vp2)
print(b, vp = vp3)
print(a, vp = vp4)

You can play around with the widths and heights to control the size of
a viewport; x and y define the center position of the viewport.

HTH,
Dennis

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>

Scott Chamberlain

unread,
May 11, 2011, 2:49:56 PM5/11/11
to Dennis Murphy, ggplot2
Dennis, 

Genius. Thanks a lot. 

Apologies; I should have thought to mess with the viewport options. 


Scott
Reply all
Reply to author
Forward
0 new messages