[R] ggplot legend consolidation

Te, Kaom Kaom.Te at schwab.com
Sat Sep 8 05:00:47 CEST 2007


Hello Everyone,
 
I have recently been introduced to the ggplot package by Hadley Wickham
and must say I am quite impressed so far at how easy it is to make
attractive plots, but one thing I am struggling over is how to
consolidate legends.
 
I have 3 plots that I would like to put on a single page and all 3 map
the same dimension of the data to the colour aesthetic.  Right now, when
I plot all three graphs on the page, I get the three graphs and three
legends. The legends are exactly the same.  I do not see a reason to
have all 3 legends and I would like to partition a section of the page
exclusively for a single legend that would apply to all graphs. 
 
How does one exract the legend for this purpose?
Does anyone know how to do this with the ggplot package?
 
Here is some example code:
------------------------------- BEGIN CODE
library(ggplot2)
data(mtcars)
 
grid.newpage()
 
pushViewport(viewport(layout = grid.layout(2, 2)))
 
p <- ggplot(data = mtcars) +
  geom_point(mapping = aes(x = hp, y = mpg, colour = cyl))
 
pushViewport(viewport(layout.pos.col = 1,
                      layout.pos.row = 1))
 
print(p, vp = current.viewport())
upViewport()
 
p <- ggplot(data = mtcars) +
  geom_point(mapping = aes(x = drat, y = disp, colour = cyl))
 

pushViewport(viewport(layout.pos.col = 2,
                      layout.pos.row = 1))
 
print(p, vp = current.viewport())
upViewport()
 
p <- ggplot(data = mtcars) +
  geom_point(mapping = aes(x = qsec, y = mpg, colour = cyl))
 
pushViewport(viewport(layout.pos.col = 1,
                      layout.pos.row = 2))
 
print(p, vp = current.viewport())
upViewport()

pushViewport(viewport(layout.pos.col = 2,
                      layout.pos.row = 2))
grid.rect()
grid.text("We want to remove\nall other legends\nand place a\nsingle one
here")
------------------------------- END CODE
 
See how there are 3 legends when there only needs to be one?   I would
like to remove the 3 legends and place them with a single legend in the
space in the lower right.
 
Thanks for your help.
 
Regards,
Kaom Te

Charles Schwab Investment Management (CSIM)
120 Kearny Street, 14th Floor
San Francisco, CA 94108
E-mail: kaom.te at schwab.com <mailto:kaom.te at schwab.com> 
 
WARNING: All email sent to or from the Charles Schwab corporate email
system is subject to archiving, monitoring and/or review by Schwab
personnel.



More information about the R-help mailing list