Search code examples
rgridextrar-grid

Curve between two rectangles is not shown


I am trying to connect the two rectangles with a curved arrow, but no curve is drawn. Could you please help me?

Thanks!

library(grid)

grid.newpage()

pushViewport(plotViewport(c(2, 2, 2, 2)))

xis <- c(0,0.25)
for (i in 1:2)
{
  grid.roundrect(x=unit(xis[i],"npc"), y=unit(1,"npc"),
                 width=1.4*stringWidth("very snug"),
                 height=1.1*unit(2, "line"),
                 just=c("left", "top"), gp=gpar(col="red"),
                 name = paste0("rectangulo",i))
  
  grid.text(paste0("very snug",i),x=xis[i]+0.005, y=unit(0.992,"npc"),
            just=c("left", "top"),name = paste0("texto",i))

  grid.text(paste0("Pedro",i),x=xis[i]+0.005, y=unit(0.95,"npc"),
            just=c("left", "top"),name = paste0("pedro",i))
  
  }

grid.curve(grobX("texto1", 0)+unit(2,"mm"), grobY("texto1", 0),
           grobX("rectangulo2", 180), grobY("pedro2", 180),
           curvature=0.5)

Solution

  • Looking at '?grobX' it says grobX() and grobY() functions need their first argument to be a

    A grob, or gList, or gTree, or gPath.

    But your code supplies character strings. After you plot your rectangles, run this code to grab and input with a gTree object, which contains the grobs of interest.

    grab <- grid.grab()
    
    grid.curve(grobX(grab$children$texto1, 0)+unit(2,"mm"), grobY(grab$children$texto1, 0),
               grobX(grab$children$rectangulo2, 180), grobY(grab$children$pedro2, 180),
               curvature=0.5)