Connecting all the points (possible conbination) in the scattering diagram

Here is a small data set:

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 to associate every possible combination between a line with a direct (Euclidean) distance in order to create some graph similar to this (preferably in the base graph or ggplot2)

enter image description here

+5
source share
2 answers

Here is a basic 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

+6
source

In ggplot you can use geom_segmentto draw connecting lines.

But first you need to build a data frame with the coordinates of each trunk. Use combn()to find all combinations:

comb <- combn(nrow(myd), 2)
connections <- data.frame(
  from = myd[comb[1, ], 1:2],
  to   = myd[comb[2, ], 1:3]
)
names(connections) <- c("x1", "y1", "x2", "y2", "label")

Then the plot:

library(ggplot2)

ggplot(myd, aes(PC1, PC2)) + 
  geom_point(col="red", size=5) + 
  geom_segment(data=connections, aes(x=x1, y=y1, xend=x2, yend=y2), col="blue")

enter image description here

+2
source

All Articles