Search code examples
rplotr-grid

How to add arrow using grid package


I want to add the arrow using grid package which will highlight the important part of my diagram. I want that the arrow will look like on the picture on the right side.

On the left part is my diagram created by the code below and on the right part is my diagram with the arrow (I've added it using Paint). It's my goal.

enter image description here

library(grid)
library(lattice)
library(sandwich)

data("Investment")
Investment <- as.data.frame(Investment)

pushViewport(plotViewport(c(5, 4, 2, 2)))
pushViewport(dataViewport(Investment$Investment, 
                      Investment$GNP,
                      name="Zaleznosc Investment od GNP"))

grid.points(Investment$Investment, Investment$GNP, gp=gpar(cex=0.5))

grid.rect()
grid.xaxis()
grid.yaxis()
grid.text("Investment", y=unit(-3, "line"))
grid.text("GNP", x=unit(-3, "line"), rot=90)
popViewport()

Solution

  • You can use the code that you have, but before popViewport() add the code to add your arrow.

    grid.lines(x = unit(c(0.42, 0.74), "npc"),
              y = unit(c(0.8, 0.86), "npc"),
            gp = gpar(fill="black"),
              arrow = arrow(length = unit(0.2, "inches"), 
                ends="last", type="closed"))
    

    Arrow

    Also, to follow up on a comment of @alistaire grid graphics are a bit hard to use. What you are trying to do is mostly easy in base graphics.

    plot(GNP ~ Investment, data=Investment)
    arrows(250, 2600, 380, 2750, code = 2, lwd=2)
    

    Base Graphics

    The only thing that is not quite perfect is the type of arrowhead. The base arrows does not give you much control over that. If you don't mind adding a package, the shape package lets you choose the style of arrowhead.

    library(shape)
    plot(GNP ~ Investment, data=Investment)
    Arrows(250, 2600, 380, 2750, code = 2, 
        arr.type="triangle", arr.width=0.4)
    

    With shape