Reputation: 2613
How can I programmatically capture the X coordinate of letter "r" in "better" string in the example? I'd like to capture that coordinate in order to dynamically draw the arrow next to it. Can this be done in R? It can be done in SAS ...with some difficulty.
x<-c(1,3)
y<-c(3,3)
plot(y~x, type="c", ylim=c(-1,5), xlim=c(-3,3), col="red")
abline(h=0,v=0, lty=3)
text(0.3, -2.5, xpd=T, "Group 1 better", adj=0)
#manually draw the arrow
arrows(x0=1.3, x1=3, y0=-2.5, y1=-2.5, length=0.1, code=2,xpd=T)
The obvious approach is to count number of letters in the string and add that number to the X coordinate of the string. This approach will probably work well in most cases but may not work well in if the size/style,angle of the text changes. I am wondering if there is a an easy way to capture the last position of the string. SAS does it by placing the arrow relative to the internal coordinates of the previous string.
I would also like to know how to capture the last coordinate of any other graphical element as well - if possible at all. Thank you
Upvotes: 1
Views: 117
Reputation: 94237
Use strwidth to get the string width, and add an extra character's width for a bit of space:
> arrowlabel = "Group 1 better")
> sw = strwidth(arrowlabel)
> xpos = 0.3 + sw + sw/nchar(arrowlabel)
Then draw your arrow starting at x=xpos.
Upvotes: 4