0

I have a distance sequence, which I would like to plot of a line in spatstat. Example:

library(spatstat)

x <- c(0.3, 5)
y <- c(3, 1.2)

range.x <- c(0, max(x)+0.2)
range.y <- c(0, max(y)+0.2)

owin <- owin(range.x, range.y)
the.line <- psp(x0 = x[1],x1 = x[2],y0 = y[1],y1 = y[2], window = owin)

plot(the.line)    

seqs <- data.frame(name = seq(1,7), distance = c(0.12, 0.3, 0.45, 0.5, 0.7, 0.89, 0.95))
lengths <- seqs$distance*lengths.psp(the.line)

I would like to plot lengths on top of the.line using seqs$name as labels in a following way (labels added with Illustrator):

enter image description here

Would anyone know how to do this? Help would be very much appreciated!

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
Mikko
  • 7,530
  • 8
  • 55
  • 92

1 Answers1

1

The text function will allow you to add text to an existing plot. Whether you can rotate the text or not depends on the graphics device that you are using, see ?par sections on 'crt' and 'srt'. Also see the 'adj' argument to text for how to get the text above the line rather than obscuring the line.

This all assumes that the plotting is being done in base graphics.

The following worked for me on windows (using the default windows graphics device) after running the code above:

x.new <- seqs$distance*x[2] + (1-seqs$distance)*x[1]
y.new <- seqs$distance*y[2] + (1-seqs$distance)*y[1]

tmp.x <- grconvertX(x, to='inches')
tmp.y <- grconvertY(y, to='inches')
theta <- atan2(diff(tmp.y),diff(tmp.x))*180/pi

text( x.new, y.new, seqs$name, adj=c(0,0), srt=theta )
Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • Well...I have used spatstat to plot and calculate my rather complex data, so the plotting needs to be done on spatstat window (owin). Besides I don't know the coordinates of my text. Only the distance along the line. – Mikko Apr 20 '12 at 12:21
  • I just ran your code above (through the plot), then used the 'locator' function and clicked on the ends of the line and the results matched with your 'x' and 'y' variable (with a little error from my clicking), so it looks like the plot is in base graphics and does not do anything fancy with the coordinates. Finding the coordinates given x and y and the distance along the line is algebra, finding the correct angle is algebra and trig, then just use the text function as above. – Greg Snow Apr 21 '12 at 17:33