Skip to content

Plotting individual pieces of a ggplot2 plot object

May 9, 2012

I often want to isolate individual pieces of a ggplot2 object (e.g. the legend), so that they can be plotted alone or in a custom arrangement. I’ve known for a while that such isolation is possible but didn’t know how to do it. Recently I discovered this website, which greatly clarified things for me. The key line of code is,

g <- ggplot_gtable(ggplot_build(p))$grobs

where p is a plot object. This code returns a list of the components of p called grobs. Here’s a simple example that plots a legend only,

require(ggplot2)
data(cars)
p <- ggplot(cars) + geom_point(aes(speed, dist, colour = speed))
g <- ggplot_gtable(ggplot_build(p))$grobs
dev.new()
pushViewport(plotViewport(rep(1, 4)))
grid.draw(g[[9]])

EDIT (see comments):


require(ggplot2)
require(grid)
data(cars)
p <- ggplot(cars) + geom_point(aes(speed, dist, colour = speed))
g <- ggplot_gtable(ggplot_build(p))$grobs
dev.new()
pushViewport(plotViewport(rep(1, 4)))
grid.draw(g[[8]])
Advertisements
2 Comments leave one →
  1. TeXi permalink
    November 28, 2012 6:00 am

    When I run the code above I get:
    NULL
    Warning message:
    In function () : Only one RStudio graphics device is permitted

    This is really a pity, because the other solutions I have found on the web are for much older versions of ggplot2…

  2. November 28, 2012 12:36 pm

    Don’t use Rstudio so couldn’t reproduce your message. However, looks like ggplot_gtable is saving things in different places, so to get the legend I needed to use g[[8]] instead of g[[9]]. Thanks for drawing my attention to this.

    As for Rstudio, your message seems to be suggesting that you should take out the dev.new()…dunno???

    R version 2.15.2 (2012-10-26)
    Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

    locale:
    [1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8

    attached base packages:
    [1] grid stats graphics grDevices utils datasets methods base

    other attached packages:
    [1] ggplot2_0.9.2.1

    loaded via a namespace (and not attached):
    [1] colorspace_1.1-1 dichromat_1.2-4 digest_0.5.2 gtable_0.1.1
    [5] labeling_0.1 MASS_7.3-22 memoise_0.1 munsell_0.3
    [9] plyr_1.7.1 proto_0.3-9.2 RColorBrewer_1.0-5 reshape2_1.2.1
    [13] scales_0.2.2 stringr_0.6.1 tools_2.15.2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: