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.
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()
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"))
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)
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)
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"))
Note that ggplot2
reexports the arrow()
function from the grid
package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With