The R arrows() function draws an arrow taking the coordinates of the origin and end point of the arrow as arguments. I need to draw an arrow using the coordinates of the origin, the length of the arrow and an angle. To do that, I have written the following function:
arrows.1 <- function(x0, y0, length.ar, angle.ar, ...){ ab <- cos(angle.ar) * length.ar bc <- sign(sin(angle.ar)) * sqrt(length.ar^2 - ab^2) x1 <- x0 + ab y1 <- y0 + bc arrows(x0, y0, x1, y1, ...) }
The function is tested on a circle:
## Circle function circle <- function(xorig, yorig, radius, add, ...){ x <- seq(-radius, radius, length.out = 1000) y <- sapply(x, function(z) sqrt(radius^2 - z^2)) if(add == TRUE){ lines(xorig + c(x, rev(x)), c(yorig + y, yorig + rev(-y)), type = "l", ...) } else { plot(xorig + c(x, rev(x)), c(yorig + y, yorig + rev(-y)), type = "l", ...) } } ## Test circle(1, 1, 1, add = FALSE) for(i in seq(0, 2 * pi, length.out = 9)){ arrows.1(x0 = 1, y0 = 1, length.ar = 1, angle.ar = i) }
Leave a comment