-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Share a legend between two ggplot2 graphs
baptiste edited this page Sep 2, 2010
·
11 revisions
Goal: align two plots, and place one or two legends on the side.
It is sometimes possible to obtain good results by creating a dummy facetting of the data as in Align-two-plots-on-a-page. For greater control, you can also use Grid to place the plots and the legends in an arbitrary layout,
Idea:
- create your two plots p1 and p2
- save the legend of p1 as a separate grob,
- strip the legend of p1 and p2,
- create three viewports on the page and print p1, p2, p3.
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
d <- qplot(carat, price, data = dsamp, colour = clarity)
p3 <- d + opts(keep = "legend_box")
p1 <- d + opts(legend.position = "none")
p2 <- d + opts(legend.position = "none")
p3
pushViewport(viewport(x = 0.4,y = 0.75, width = 0.8, height = 0.5,
angle = 0, name = "topleftvp"))
grid.rect()
print(p1, vp = "topleftvp")
upViewport()
pushViewport(viewport(x = 0.4,y = 0.25, width = 0.8, height = 0.5,
angle = 0, name = "botleftvp"))
grid.rect()
print(p2, vp = "botleftvp")
upViewport()