Search code examples
rggplot2scatter-plotedges

Using ggplot to link points of interest in scatterplot


I am trying to create a scatterplot, and then add lines between points in the scatterplot. I can get this to work using plot and segments, as shown below:

set.seed(10)
xvar = runif(10, 0, 1)
yvar = runif(10, 0, 1)

start = c(1, 1, 1, 9)
end = c(2, 4, 6, 10)

plot(xvar, yvar)
segments(xvar[start], yvar[start], xvar[end],yvar[end], col= 'blue')

I would like to achieve the same type of idea, but with using ggplot2. My reasoning for this is that I may want to add aesthetics to the plot, and ggplot2 allows this more than plot. I tried variants of:

ggplot(dat, aes(x = xvar, y = yvar)) +
  geom_point(shape=20, size=1) +
  segments(xvar[start], yvar[start], xvar[end], xvar[end], col = 'blue')

But to no avail. Any pointers would be very much appreciated!


Solution

  • The idea is to use geom_line and to define groups (gr) for every segment:

    dat <- data.frame(xvar = xvar, yvar = yvar)    
    dat2 <- cbind(dat[c(start, end), ], gr = 1:length(start))
    
    ggplot(dat, aes(x = xvar, y = yvar)) + geom_point(shape = 20, size = 1) +
      geom_line(aes(x = xvar, y = yvar, group = gr), data = dat2)
    

    enter image description here