在R绘图中,在x轴下方添加箭头

9

我正在尝试在R绘图中添加标记特定x坐标的箭头。我的x轴在y=0处,当我尝试使用负y坐标在arrows中,使箭头垂直于x轴时,我只得到了箭头的边缘部分(尽管有些空间,例如绘制x轴标签和刻度线的地方)。

2个回答

11

xpd选项可以在箭头中使用,因此您可以将坐标设置为在绘图区域之外,并将xpd设置为TRUE。例如,假设xlim = c(0,10)和ylim =(0,10),并且您将x轴设置为0,则

arrows(1.4, -1, 1.4, 0, xpd = TRUE)

在x轴的1.4位置绘制一个指向上方的竖直箭头。


这种方法唯一的问题是,如果你调整图表的大小(我使用的是Rstudio),箭头就会出现问题。 - ECII
这种情况通常发生在图例、各种元素的相对定位上...你只需要再次运行你的绘图命令即可。 - John

3

您可以通过添加额外的叠加层,调用 par(new=TRUE) 并减少边距来实现此操作。例如:

plot(1,1) ## start a plot
opar <- par(new = TRUE, ## add a new layer
            mar = c(0,0,0,0)) ## with no margins margins
## set up the plotting area for this layer
plot(1,1,xlim=c(0,1),ylim=c(0,1),type='n',xlab='',ylab='') 
arrows(0.1,0.05,0.5,0.05) ## add arrow
par(opar) ## return the plot parameters to their prior values

编辑:如果你想保持原始图中的坐标系,你需要谨慎选择x轴和y轴的限制。这在下面给出了说明:

plot(1,1,xlim=0:1,ylim=0:1)
arrows(0.1,0.05,0.5,0.05)
gpar <- par()
opar <- par(new = TRUE, mar = c(0,0,0,0),xaxs='i',yaxs='i')

m1 <- (gpar$usr[2] - gpar$usr[1])/(gpar$plt[2] - gpar$plt[1])
c1 <- gpar$usr[1] - m1*gpar$plt[1]
m2 <- (gpar$usr[4] - gpar$usr[3])/(gpar$plt[4] - gpar$plt[3])
c2 <- gpar$usr[3] - m2*gpar$plt[3]
xlim <- c(c1, m1 + c1)
ylim <- c(c2, m2 + c2)

plot(1,1,xlim=xlim,ylim=ylim,type='n',xlab='',ylab='')
arrows(0.1,0.05,0.5,0.05,col='red')
points(1,1,col='red')
par(opar)

+1 谢谢,但是我该如何在原始图中绘制特定 x 坐标上的箭头呢?在调用 par(new=TRUE) 之前,如果我绘制箭头(10,1,20,1),它将在我的图形坐标系中从 (10,1) 到 (20,1);在调用 par(new=TRUE) 之后,我需要以某种方式将新坐标转换为旧坐标... - David B
谢谢!我认为这种事情很普遍。 - David B
实际上,我自己从未必须这样做。可能有更简洁的方法。 - nullglob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接