If you want to do this in ggplot2
, you can use geom_segment
for this. But before you can make such a plot, you need to create a data frame that links each observation with other observations. You can approach it as follows:
library(ggplot2) library(dplyr) library(tidyr) dat %>% complete(nesting(x,y), id) %>%
which gives:

Used data:
dat <- data.frame(x = c(5,1,3,2,5,7,12), y = c(5,7,6,1,3,5,6)) dat$id <- 1:nrow(dat)
Alternatively, you can also add the line identifier on the fly without doing this in advance:
dat %>% mutate(id = row_number()) %>%
source share