Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add arrow using grid package

Tags:

plot

r

r-grid

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()
like image 716
Viola Avatar asked Jan 12 '18 02:01

Viola


2 Answers

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

like image 168
G5W Avatar answered Oct 22 '22 01:10

G5W


In his comment, @alistaire has mentioned ggplot2 as an alternative to working with grid directly.

For the sake of completeness, here is a ggplot2 version which uses the annotate() function to place an arrow on the chart.

data(Investment, package = "sandwich")

library(ggplot2)
ggplot(as.data.frame(Investment)) +
  aes(Investment, GNP) +
  geom_point(shape = 1L) +
  theme_bw() +
  annotate("segment", x = 250, xend = 380, y = 2600, yend = 2800, 
           arrow = arrow(length = unit(0.2, "inches"), ends = "last", type = "closed"))

enter image description here

Note that ggplot2 reexports the arrow() function from the grid package.

like image 44
Uwe Avatar answered Oct 22 '22 02:10

Uwe