使用R

时间:2019-01-25 21:29:50

标签: r gis igraph

我想使用简单的工具包(例如maptools或maps)在地理地图上绘制最小生成树,并将生成的树保存在shapefile中,以便使用GIS进行进一步处理。最小生成树是根据一组经度/纬度十进制坐标表示的位置计算出来的(请参见下面的测试数据集)。使用package igraph并遵循here提供的(相当复杂的)示例,我已经能够计算最小生成树,但是:(i)我不知道如何在地图上绘制它; (ii)我看不到如何将其另存为shapefile;通过解决后一个问题,我可以(大概)能够解决前一个问题,因为我可以使用rgdal等程序简单地读取和绘制shapefile。对用户定义的mst2lines()函数的调用返回边列表应该可以解决问题的方法,我只是看不到。

这是我的示例代码:

library(igraph)
library(geosphere)

# This is from [here][1]
mat2list <- function(D) {
  n = dim(D)[1]
  k <- 1
  e <- matrix(ncol = 3,nrow = n*(n-1)/2)
  for (i in 1:(n-1)) {
    for (j in (i+1):n) {
      e[k,] = c(i,j,D[i,j])
      k<-k+1
    }
  }
  return(e)
}

# This is from [here][1]
mst2lines <- function(mst,lonlat) {
  me = get.edges(mst,1:ecount(mst))
  R = data.frame(lon=NULL,lat=NULL,group=NULL)
  for (k in 1:ecount(mst)) {
    A = lonlat[me[k,],]
    A$group = k
    R <- rbind(R,A)
  }
  rownames(R) <- NULL
  return(R)
}

# Read data
df <- read.csv("zygo.csv", header=TRUE)
lonlat <- data.frame(df$Longitude, df$Latitude)
colnames(lonlat) <- c("lon", "lat")
names <- as.vector(df$Locality)

# Localities as a list of graph vertices
v <- data.frame(ids=c(1:15), name=as.vector(df$Locality), x=df$Longitude, y=df$Latitude)

# Set the extent of the map
range <- (apply(lonlat,2,max) - apply(lonlat,2,min))*.10
xlimits = c(min(lonlat$lon)-range[1],max(lonlat$lon)+range[1]) 
ylimits = c(min(lonlat$lat)-range[2],max(lonlat$lat)+range[2]) 

# Compute distance matrix between pairs of localities
D <- distm(lonlat, lonlat, fun=distVincentyEllipsoid)
eD = mat2list(D/1000)

# Create the minimum spanning tree
net <- graph.data.frame(eD[,1:2], directed = FALSE, vertices = v)
E(net)$weight <- eD[,3] # Important use edge weight rather than net$weight
mst <- minimum.spanning.tree(net)
R = mst2lines(mst, lonlat)

# Plot localities on the map
library(maptools)
data(wrld_simpl)
plot(wrld_simpl, xlim=xlimits, ylim=ylimits, axes=TRUE, col="grey95",
     xlab="Longitude", ylab="Latitude")
points(x=df$Longitude, y=df$Latitude, col="red", pch=19, cex=0.75)
box()

这是我的测试数据。

"Scientific name",Locality,Longitude,Latitude
Zygodontmys,Bush Bush Forest,-61.05,10.4
Zygodontmys,Cerro Azul,-79.4333333333,9.15
Zygodontmys,Dividive,-70.6666666667,9.53333333333
Zygodontmys,Hato El Frio,-63.1166666667,7.91666666667
Zygodontmys,Finca Vuelta Larga,-63.1166666667,10.55
Zygodontmys,Isla Cebaco,-81.1833333333,7.51666666667
Zygodontmys,Kayserberg Airstrip,-56.4833333333,3.1
Zygodontmys,Limao,-60.5,3.93333333333
Zygodontmys,Montijo Bay,-81.0166666667,7.66666666667
Zygodontmys,Parcela 200,-67.4333333333,8.93333333333
Zygodontmys,Rio Chico,-65.9666666667,10.3166666667
Zygodontmys,San Miguel Island,-78.9333333333,8.38333333333
Zygodontmys,Tukuko,-72.8666666667,9.83333333333
Zygodontmys,Urama,-68.4,10.6166666667
Zygodontmys,Valledup,-72.9833333333,10.6166666667

在此先感谢您提供任何提示或建议。

编辑。我附上一张描述我想要的地图的图像。该图是通过从shapefile中读取使用Python创建的最小生成树而创建的(抱歉)。

enter image description here

0 个答案:

没有答案