1

I've been trying (knowing all the reasons why I shouldn't) to overlay two graphs on each other. I remember that when I used viewports in the past the two images would overlay on top of each other. So grid wouldn't overwrite one graphic with the other. In the MWE below, one graphic is deleted when I try and print the second over it.

What am I doing wrong? Thanks

library(grid)
library(ggplot2)

date=seq(as.Date('2012-04-01',"%Y-%m-%d"),as.Date('2013-03-27','%Y-%m-%d'),1)
tp1=data.frame(Date=date,bond=rnorm(361,100,2),equity=rnorm(361,60,15))
vp=viewport(x=0.5,y=0.5,height=1,width=1)
a = ggplot(tp1,aes(Date,bond)) + geom_line(colour=I("blue")) + xlim(range(tp1$Date))
b = ggplot(tp1,aes(Date,equity)) + geom_line(colour=I("red")) + xlim(range(tp1$Date))
print(a,vp=vp)
print(b,vp=vp)
4

1 回答 1

4

I don't see how using just viewports you can overlay the 2 ggplot2 plots. Maybe you did this using some simple grid graphics, not with ggplot2 plots that are complex (many viewports with a lot of details). Viewports are just a context where you basically define the dimensions/scales of your plot.

Here, a hadley code doing what you want. I just add a small part and adapt it using your plot instructions.

enter image description here

The all code is :

library(ggplot2)
library(grid)
library(gtable)

grid.newpage()

# two plots
a = ggplot(tp1,aes(Date,bond)) + geom_line(colour=I("blue")) + xlim(range(tp1$Date))
b = ggplot(tp1,aes(Date,equity)) + 
  geom_line(colour=I("red")) + 
  theme(panel.background = element_rect(fill = NA))

# extract gtable
g1 <- ggplot_gtable(ggplot_build(a))
g2 <- ggplot_gtable(ggplot_build(b))

# overlap the panel of 2nd plot on that of 1st plot
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, 
                     pp$l, pp$b, pp$l)

## what I dd is to plot a new viewports.
vp=viewport(x=0.5,y=0.5,height=0.5,width=0.5)
pushViewport(vp)
grid.draw(g)
upViewport()
于 2013-04-28T12:24:20.803 回答