Skip to content

Instantly share code, notes, and snippets.

@ericnovik
Last active August 23, 2022 17:25
Show Gist options
  • Save ericnovik/d07c883545f98b336f3855a2bab87421 to your computer and use it in GitHub Desktop.
Save ericnovik/d07c883545f98b336f3855a2bab87421 to your computer and use it in GitHub Desktop.
draw_vector <- function(x, ...) {
df <- data.frame(x1 = x[1], x2 = x[2])
a <- arrow(length = unit(0.03, "npc"))
dims <- ceiling(abs(max(x)))
p <- ggplot() + xlim(-dims, dims) + ylim(-dims, dims)
p <- p + geom_segment(aes(x = 0, y = 0, xend = x1, yend = x2),
arrow = a, data = df, ...) +
geom_hline(yintercept = 0, size = 0.1) +
geom_vline(xintercept = 0, size = 0.1)
return(p)
}
add_vector <- function(p, x, ...) {
df <- data.frame(x1 = x[1], x2 = x[2])
dims_x <- ceiling(abs(max(x)))
dimx_p <- ceiling(abs(layer_scales(p)$x$range$range))
dimy_p <- ceiling(abs(layer_scales(p)$y$range$range))
dims <- max(c(dims_x, dimx_p, dimy_p))
a <- arrow(length = unit(0.03, "npc"))
p <- p + geom_segment(aes(x = 0, y = 0, xend = x1, yend = x2),
arrow = a, data = df, ...) +
xlim(-dims, dims) + ylim(-dims, dims)
return(p)
}
# rotate a vector
rotate <- function(v, theta) {
R <- matrix(c(cos(theta), sin(theta),
-sin(theta), cos(theta)), ncol = 2)
return(R %*% v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment