如何在行()中添加其他字符,如箭头?

时间:2016-08-15 15:34:09

标签: r plot

此问题解释了如何使用lines()制作不同的线型:How to define more line types for graphs in R?

但是,这只是线条的间距和长度。我想绘制一条显示方向的线,所以线型如---->---->---->---。是否可以使用lines()

绘制这样的一行

1 个答案:

答案 0 :(得分:3)

您可以绘制虚线,然后使用arrows功能添加自定义间距箭头。例如:

假设您有两条曲线(例如,来自两个回归模型):

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

在k点插入这两条曲线:

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

如果你打算经常这样做,你可以将上面的代码概括为一个函数,在曲线上取点并用破折号和箭头绘制它们。

enter image description here