2012-08-05 39 views
1

使用this作爲參考,我試圖繪製一個較低的四十八個地圖,並添加圖層以可視化狀態之間的流動。如何在ggplot地圖上添加地理空間連接?

library(ggplot2) 
library(maps) 
library(geosphere) # to inter-polate a given pair of (lat,long) on the globe 

# load map data for the US 
all_states <- map_data("state") 

# plot state map 
p <- ggplot() + geom_polygon(data=all_states, 
         aes(x=long, y=lat, group = group), 
         colour="white", fill="grey10") 

# sample origin - destination lat,long pairs 
geo <- structure(list(orig_lat = c(36.17, 36.17, 36.17), 
orig_lon = c(-119.7462, -119.7462, -119.7462), dest_lat = c(33.7712, 36.17, 39.0646), 
    dest_lon = c(-111.3877, -119.7462, -105.3272)), .Names = c("orig_lat", 
"orig_lon", "dest_lat", "dest_lon"), row.names = c(NA, 3L), class = "data.frame") 

#> geo 
# orig_lat orig_lon dest_lat dest_lon 
#1 36.17 -119.7462 33.7712 -111.3877 
#2 36.17 -119.7462 36.1700 -119.7462 
#3 36.17 -119.7462 39.0646 -105.3272 

# list to hold a dataframe of interpolated points for each origin-destination pair 
list_lines <- list() 

# use the geosphere package's gcIntermediate function to generate 50 interpolated 
# points for each origin-destination pair 
for (i in 1:3) { 
    inter <- as.data.frame(gcIntermediate(c(geo[i,]$orig_lon, geo[i,]$orig_lat), 
             c(geo[i,]$dest_lon, geo[i,]$dest_lat), 
             n=50, addStartEnd=TRUE)) 
    list_lines[i] <- list(inter) 
    p <- p + geom_line(data = list_lines[[i]], aes(x = lon, y = lat), color = '#FFFFFF') 
} 
p 

這裏是我所得到的,當我嘗試打印情節

p 
Error in eval(expr, envir, enclos) : object 'lon' not found 

我試圖調試這,發現這個工作

p + geom_line(data = list_lines[[1]], aes(x = lon, y = lat), color = '#FFFFFF') 

但加入第二另一層list元素會破壞它,但就我對R和ggplot的有限知識而言,這是我能得到的!

回答

3

gcIntermediate返回不同的列名(由於出發地和目的地是對於i相同= 2):

for (i in 1:3) { 
    inter <- as.data.frame(gcIntermediate(c(geo[i,]$orig_lon, geo[i,]$orig_lat), 
             c(geo[i,]$dest_lon, geo[i,]$dest_lat), 
             n=50, addStartEnd=TRUE)) 
    print(head(inter, n=2)) 
} 
    lon lat 
1 -119.7 36.17 
2 -119.6 36.13 
     V1 V2 
1 -119.7 36.17 
2 -119.7 36.17 
    lon lat 
1 -119.7 36.17 
2 -119.5 36.24 

以下各行應工作:

for (i in 1:3) { 
    inter <- as.data.frame(gcIntermediate(c(geo[i,]$orig_lon, geo[i,]$orig_lat), 
             c(geo[i,]$dest_lon, geo[i,]$dest_lat), 
             n=50, addStartEnd=TRUE)) 
    names(inter) <- c("lon", "lat") 
    p <- p + geom_line(data=inter, aes(x=lon, y=lat), color='#FFFFFF') 
} 
+0

這是相當愚蠢的我!解決了這個問題,謝謝! – JConnor 2012-08-05 11:40:57

1

令我感到奇怪的是,您以兩種不同的方式參考經度:long在腳本的開頭,lon到最後。如果您希望多個geom一起工作,則需要使這些名稱保持一致。

此外,添加相同的geom與for循環幾乎是不需要的。只需添加一個geom_line並使用color美學繪製多條線。

0

存在使用ggplot2一個非常簡單的解決方案。有一個簡單的教程,介紹如何在R中使用ggplot2,here繪製流程圖。

p + 
    geom_segment(data = geo, aes(x = orig_lon, y = orig_lat, 
           xend = dest_lon, yend = dest_lat, 
           color="#FFFFFF")) + coord_equal() 

enter image description here