3

I have two ggplot2 plots and I want to draw a series (10-100) slightly different curves between them. That is, I will have a two-panel layout and want to draw connecting lines from the left plot to the right plot. So far I have tried doing this by converting things to grob's and using the gtable package to add curves.

To illustrate, I have something like:

library(ggplot2)
library(gtable)
library(grid)
library(gridExtra)
p1 = ggplot(data.frame(x=1:10,y=1:10),aes(x=x,y=y))+geom_point()
p2 = ggplot(data.frame(x=1:10,y=1:10),aes(x=x,y=y))+geom_point()
g1 = ggplotGrob(p1)
g2 = ggplotGrob(p2)
gt = gtable:::cbind.gtable(g1,g2,size='first')
gt$heights = unit.pmax(g1$heights,g2$heights)
for(i in 1:10) {
  gt = gtable_add_grob(gt,curveGrob(0,0.5,1,0.5,ncp=5,square=FALSE,curvature=i/10),l=5,r=8,b=3,t=3)
}
grid.newpage()
grid.draw(gt)

producing a plot like this:

output

which is almost right, except only the last of the curveGrob objects is shown. I've tried playing around with the z-index for the added grobs and the last one plotted always overwrites the others. I want my plot to look the same, except it should show all 10 curves between the two plot areas, instead of just the one that is showing with my existing code.

So how can I either modify my existing code to show all 10 curves or achieve the same effect by using a different method? I am stuck using ggplot2 for the main plots, as they are considerably more complex than the toy example shown.

eipi10
  • 91,525
  • 24
  • 209
  • 285
user1356855
  • 565
  • 2
  • 5
  • 11
  • Possible duplicate of [ggplot, drawing line between points across facets](http://stackoverflow.com/questions/31690007/ggplot-drawing-line-between-points-across-facets) – jaimedash Apr 21 '16 at 18:47
  • 1
    I don't think it's a duplicate, because the issue here is getting multiple curve grobs to display when added at the same l,r,b, and t coordinates. In fact, this works in the for loop: `gt = gtable_add_grob(gt,curveGrob(0,0.5,1,0.5,ncp=5,square=FALSE,curvature=i/10),l=5,r=8,b=3,t=3+i/11)`. I'm not sure why slightly changing the t position works and the original code doesn't. It's not a clipping issue AFAICT. – eipi10 Apr 21 '16 at 21:09

1 Answers1

2

gtable wants unique names for grobs that are in the same position

  gt = gtable_add_grob(gt,curveGrob(0,0.5,1,0.5,ncp=5,square=FALSE,curvature=i/10),
            l=5,r=8,b=3,t=3, name=paste(i))

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294