Niek de Klein - 2 months ago 5x
R Question

# How to add other characters in lines()?

This question explains how to make different line types with lines(): How to define more line types for graphs in R?

However, this is only the spacing and length of the lines. I would like to plot a line which shows direction, so a linetype like

`---->---->---->---`
. Is it possible to plot such a line with
`lines()`
?

You can plot dashed lines and then add arrow heads. For example:

Say you have two curves (for example, from two regression models):

``````dat = data.frame(x = 0:20, y1 = 3*0:20 + 5, y2 = 0.5*(0:20)^2 - 2*0:20 + 3)
``````

Interpolate those two curves at k points:

``````k=100
di1 = as.data.frame(approx(dat\$x,dat\$y1, xout=seq(min(dat\$x), max(dat\$x), length.out=k)))
di2 = as.data.frame(approx(dat\$x,dat\$y2, xout=seq(min(dat\$x), max(dat\$x), length.out=k)))
``````

Plot dashed lines:

``````plot(y ~ x, data=di1, type="l", lty=2, xlim=range(dat\$x), ylim=range(c(dat\$y1,dat\$y2)))
lines(y ~ x, data=di2, type="l", lty=2, col="red")
``````

``````n = 10
arrows(di1\$x[which(1:nrow(di1) %% n == 0) - 1], di1\$y[which(1:nrow(di1) %% n == 0) - 1],
di1\$x[1:nrow(di1) %% n == 0], di1\$y[1:nrow(di1) %% n == 0] - 0.01,
length=0.1)
arrows(di2\$x[which(1:nrow(di2) %% n == 0) - 1], di2\$y[which(1:nrow(di2) %% n == 0) - 1],
di2\$x[1:nrow(di2) %% n == 0], di2\$y[1:nrow(di2) %% n == 0] - 0.01,
length=0.1, col="red")
``````

If you plan on doing this frequently, you can generalize the above code into a function takes points on a curve and plots them with dashes and arrow heads.

Source (Stackoverflow)