如何使用R连接地图的所有点

时间:2014-10-15 17:56:09

标签: r ggplot2 maps

我希望制作一张地图,显示点并将其中的每一个与其他人连接,例如网络。我知道我必须使用某种循环或组合,但我在最后一步堆叠。拜托,谢谢你的帮助。提前谢谢!

setwd("C:/data")

# Plot a simple map of the Spanish-French border without any detail
xlim <- c(-3.36, 4.78)
ylim <- c(40.17, 44.63)
map1 <- map("world", col="#f2f2f2", fill=TRUE, bg="white", lwd=0.05, xlim=xlim, ylim=ylim)

# Plot nodes
locations <- read.csv("locations.csv", sep=";")
symbols(locations$longitude, locations$latitude, bg="#e2373f", fg="#ffffff", lwd=0.5, circles=rep(1, length(locations$longitude)), inches=0.05, add=TRUE)

# Plot links [here is where I need your HELP!], the following code do not achieve my goal...
for (i in 2: length(locations$longitude)-1) {
  lngs <- c(locations$longitude[i], locations$longitude[i+1])
  lats <- c(locations$latitude[i], locations$latitude[i+1])
  lines(lngs, lats, col="#e2373f", lwd=2)

1 个答案:

答案 0 :(得分:0)

这是一次尝试(我还没有测试过这段代码):

connectTheDots <- function(index) {
  remainingIndices <- (index + 1):nrow(locations)
  for (j in remainingIndices) {
    lngs <- c(locations[index, "longitude"], locations[j, "longitude"])
    lats <- c(locations[index, "latitude"], locations[j, "latitude"])
    lines(lngs, lats, col="#e2373f", lwd=2)
  }
}

for (i in 1:nrow(locations)) {
  connectTheDots(i)
}

# this is essentially a nested for loop,
# but I tried to make the syntax simpler by making a function first