连接最近邻点

时间:2015-01-06 22:07:15

标签: r lines nearest-neighbor

我有30个数据点(图中的绿点)的x-y坐标列表,我想将它们连接在一起。

plot

我怎样才能在R中做到?目前,我计算了每个点之间的距离矩阵dist(),以获得每个点的最近邻居。然而,这导致30个边缘对...有时多个边连接到同一个点,这不是我想要的:(如何在R中解决这个问题?

  cities_num=10
  cor.matrix=matrix(0,nrow=cities_num,ncol=2)
  for (r in 1:cities_num){
  cor.matrix[r,]=c(sample(1:500, 1),sample(1:500, 1))}
  par(mar=c(4,4,2,4))
  plot(cor.matrix,pch=4,xlab="X coordinate",ylab="Y coordinate")
  centroid.x=mean(cor.matrix[,1])
  centroid.y=mean(cor.matrix[,2])
  bead_num=cities_num+20
  t=seq(0,pi*2,length=bead_num) 
  coords=t(rbind( centroid.x+sin(t)*10, centroid.y+cos(t)*10))
  for (point in 1:bead_num){
    symbols(x=coords[,1][point],y=coords[,2][point],circles=0.5,
            inches = FALSE, add = TRUE)
  }

1 个答案:

答案 0 :(得分:0)

不确定"符号是什么"是的,你的代码中似乎有太多未定义的对象,所以我创建了自己的"点"。如果只是常规点,请使用polygon

 dat <- data.frame(s=sin(seq(pi,-pi,length=25)),
                    c=cos(seq(pi,-pi,length=25)) )
 png();
     plot(0,0, xlim=c(-1.5,1.5),ylim=c(-1.5,1.5) );
       with(dat, points(s,c));
       with(dat, polygon(s,c) ) 
 dev.off()

enter image description here

相关问题