0
votes

I'm looking for a way to represent a vector coming off of a point given angle and magnitude in ggplot. I've calculated what the endpoint of these vectors should be, but can't figure out a way to plot this properly in ggplot2. In short, given an observation with (X,Y,vec.x,vec.y), how can I plot a line from (X,Y) to (vec.x,vec.y) that does not show (vec.x,vec.y)?

My first instinct was to use geom_line, but this seems to rely on connecting different observations, so I would need to separate each observation into two observations, one with the original point and one with the vector endpoint. However, this seems fairly messy and like there should be a cleaner way to achieve this. Furthermore, this would make it complicated to show the original points but hide the vector points, as they would be plotted within the same geom_point call.

Here's a sample dataset in the form I'm talking about:

test <- tibble(
  x = c(1,2,3,4,5),
  y = c(5,4,3,2,1),
  vec.x = c(1.5,2.5,3.5,4.5,5.5),
  vec.y = c(4,3,2,1,0)
)

test %>%
  ggplot() +
  geom_point(aes(x=x,y=y),color='red') +
  geom_point(aes(x=vec.x,y=vec.y),color='blue')

What I'm hoping to achieve is this, but without the blue dots: 1

Any thoughts? Apologies if this is a duplicated issue. I did some Googling and was unable to find a similar question for ggplot.

1
You can use geom_segment to add the arrow.juby

1 Answers

1
votes
test %>%
    ggplot() +
    geom_point(aes(x=x,y=y),color='red') +
    geom_point(aes(x=vec.x,y=vec.y),color='blue') +
    geom_segment(
        aes(x = x,y = y, xend = vec.x,yend = vec.y),
        arrow = arrow(length = unit(0.03,units = "npc")),
        size = 1
    )

enter image description here

Reference: https://ggplot2.tidyverse.org/reference/geom_segment.html