Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add other characters, such as arrow heads, in lines()?

Tags:

plot

r

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()?

like image 898
Niek de Klein Avatar asked Aug 15 '16 15:08

Niek de Klein


1 Answers

You can plot dashed lines and then add custom-spaced arrow heads with the arrows function. 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")

Add arrow heads at every tenth point:

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.

enter image description here

like image 105
eipi10 Avatar answered Oct 19 '22 14:10

eipi10