在散点图

问题描述:

在这里连接的所有点(可能conbination)是小数据集:在散点图

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) 

我想和直的(欧几里得)距离连接线之间的所有可能的组合,以产生一些图形像这样(最好在基图形或GGPLOT2)

enter image description here

这里是碱情节溶液:

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

这里是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)) 

enter image description here

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

enter image description here