Search code examples
rplotline

connecting all points (possible conbination) in scatter plot


Here is small dataset:

myd <- data.frame(PC1 = rnorm(5, 5, 2), 
PC2 = rnorm (5, 5, 3), label = c("A", "B", "C", "D", "E"))
plot(myd$PC1, myd$PC2)
text( myd$PC1-0.1, myd$PC2, lab = myd$label)

I want connect all possible combination between line with straight (euclidean) distance, to produce some graph like this (preferrably in base graphics or ggplot2)

2D graph with five points, with a line drawn from each point to each other point


Solution

  • Here is the base plot solution:

    plot(myd$PC1, myd$PC2)
    apply(combn(seq_len(nrow(myd)), 2), 2, 
          function(x) lines(myd[x, ]$PC1, myd[x, ]$PC2))
    

    enter image description here

    Here is the ggplot2 solution:

    ps <- data.frame(t(apply(combn(seq_len(nrow(myd)), 2), 2, 
                             function(x) c(myd[x, ]$PC1, myd[x, ]$PC2))))
    qplot(myd$PC1, myd$PC2) +
      geom_segment(data = ps, mapping = aes(x = X1, xend = X2, y = X3,yend = X4))
    

    enter image description here