Link 段与 R 中的列值匹配

Link segments matched by column value in R

你好

我正在尝试绘制分段线并通过匹配值连接它们。

我已经根据 "Start" 和 "End" 值绘制了 R 中的 x 坐标和 Group 作为 y 坐标的线段。如果它们共享,我想用一条线连接这些线段与我的示例数据集 data:

所示相同 "id"
Name  Start   End      Group   ID

TP1   363248  366670   7       98

TP2   365869  369291   11      98

TP3   366459  369881   1       98

AB1   478324  481599   11      134

AB2   478855  482130   1       134

AB3   480681  483956   10      134

JD1   166771  169764   6       214

JD2   386419  389244   7       214

JD2   389025  391850   11      214

到目前为止,我使用 data 的结果是:

x <- seq(0, 4100000, length = 200)
y <- seq(0, 15, length = 200)
plot(x,y,type="n");

start.x <- (data[,2])
end.x   <- (data[,3])
end.y   <- start.y <- (data[,4]) # from and to y coords the same

segments(x0 = start.x, y0 = start.y, x1 = end.x, y1 = end.y)

lines(data[,1], data[,5]) 

我的线段绘制得很好,但我的连接线没有出现。关于如何绘制连接线有什么建议吗?非常感谢你。

在下面的代码中,我使用 xlimylim 参数放大了绘图,以便我们可以更好地查看绘图数据。

如您所见,我正在使用 for 循环迭代每个唯一的 ID 值。对于每个值,我使用 combn() 获得组中所有记录对的组合。然后我使用 apply() 遍历每个组合。对于每个组合,我调用 segments() 在两个(原始)线段的中心之间绘制一条线段。我为每个组使用不同的颜色,以便轻松区分它们。

df <- data.frame(Name=c('TP1','TP2','TP3','AB1','AB2','AB3','JD1','JD2','JD2'),Start=c(363248,365869,366459,478324,478855,480681,166771,386419,389025),End=c(366670,369291,369881,481599,482130,483956,169764,389244,391850),Group=c(7,11,1,11,1,10,6,7,11),ID=c(98,98,98,134,134,134,214,214,214));
xlim <- c(min(df$Start),max(df$End));
ylim <- c(min(df$Group),max(df$Group));
plot(NA,xlim=xlim,ylim=ylim,xlab='x',ylab='y');
start.x <- df[,'Start'];
end.x <- df[,'End'];
end.y <- start.y <- df[,'Group'];
segments(start.x,start.y,end.x,end.y);
uid <- unique(df$ID);
cols <- rainbow(length(uid));
for (i in seq_along(uid)) {
    df.sub <- subset(df,ID==uid[i]);
    col <- cols[i];
    apply(combn(nrow(df.sub),2),2,function(ris) {
        r1 <- df.sub[ris[1],];
        r2 <- df.sub[ris[2],];
        segments(mean(c(r1$Start,r1$End)),r1$Group,mean(c(r2$Start,r2$End)),r2$Group,col=col);
    });
};