5

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)

enter image description here

4

2 回答 2

6

这是基本情节解决方案:

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

在此处输入图像描述

这是 ggplot2 解决方案:

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))

在此处输入图像描述

于 2012-07-13T14:43:33.547 回答
2

在 ggplot 中,您可以使用它geom_segment来绘制连接线。

但首先你必须用每条连接线的坐标构建一个数据框。用于combn()查找所有组合:

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")

然后绘制:

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")

在此处输入图像描述

于 2012-07-13T14:48:30.110 回答