I am trying to add arrows marking specific x coordinates below the x axis in an R plot. My x axis is at y=0 and when I try to use negative y-coordinates in arrows
, so the arrows will be perpendicular to x axis, I get only the very edges of the arrow plotted (although is some space, e,g where the x-axis label and tickmarks are plotted).
views:
85answers:
2
+2
A:
You can do this by adding an extra overlay, by calling par(new=TRUE)
, with reduced margins. For example:
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
Edit: If you want to keep the same coordinates as in the original plot, you have to choose the x- and y-axis limits carefully. This is illustrated belo:
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)
nullglob
2010-08-06 11:05:58
+1 Thanks, but how can I plot my arrows on a specific x-coordinate in the original plot? Before calling `par(new=TRUE)`, if I draw arrows(10,1,20,1) it would go from (10,1) to (20,1) in my graph coordinate system; after calling `par(new=TRUE)` I need to somehow convert new coordinates to old ones...
David B
2010-08-06 11:39:12
Thank you! I thought this kind of thing is quite common.
David B
2010-08-06 15:22:10
Actually, I've never had to do it myself. There is probably a neater way of doing it.
nullglob
2010-08-06 15:30:27
+1
A:
The xpd option can be used in arrows so you can just set your coordinates to be outside your plot region and set xpd to TRUE. For example, assuming xlim = c(0,10) and ylim = (0,10), and you set the x-axis to 0 then
arrows(1.4, -1, 1.4, 0, xpd = TRUE)
draws a vertical arrow pointing up at the x-axis at position 1.4 on that axis.
John
2010-08-06 21:33:13