2016-07-25 106 views
1

我正在试图在R中绘制各地点的地理坐标图,然后在它们之间的箭头指示特定的航班路线。如何在地图上用ggmap绘制R中的地图上的箭头

据对堆栈溢出这里一些早期的问题,这应该是可能使用ggmap和geom_segment,但它采用的方法,我在我下面的代码看起来像它不会工作:

library(htmlwidgets) 
library(leaflet) 
library(ggmap) 


#=============================== Data ===============================# 


#Retrieving coordinates for two airports 
Adress = c("Lufthavnsboulevarden 6, 2770 Kastrup, Denmark", "Edvard Munchs veg, 2061 Gardermoen, Norway") 

# This function geocodes a location (find latitude and longitude) using the Google Maps API 
geo <- geocode(location = Adress, output="latlon", source="google") 

#moving the data around, so that second observation will be end-destination 
geo$lonend[1] <- geo$lon[2] 
geo$latend[1] <- geo$lat[2] 

#removing second row 
row_to_keep = c(TRUE, FALSE) 
geo = geo[row_to_keep,] 

#putting a number in there to make some dots for the airports 
geo$Number = 999 

#=============================== Ploting =============================# 

# get a Google map 
require(ggmap) 
map<-get_map(location='Europe', zoom=5, maptype = "terrain", 
      source='google',color='color') 

# plot it with ggplot2 
require("ggplot2") 
require("RColorBrewer") 
ggmap(map) + 
    geom_point(
    aes(x=lon, 
     y=lat, 
     show_guide = TRUE, 
     colour=Number), 
    data=geo, 
    alpha=.8, 
    na.rm = T) + 
    scale_color_gradient(low="beige", high="blue") 

#Set the pointer from (y,x) => (yend,xend) using geom-segment 
ggmap(map, extent = "device", ylab = "lat", xlab = "lon") + 
    geom_segment(aes(y = geo$lon, x = geo$lat, yend = geo$lonend, xend = geo$latend)) 

你有对于我做错了什么的建议?

回答

1

您的细分未被绘制,因为您将经度和纬度混淆,x对应于经度,y对应于纬度。此外,你应该使用data = geoaes()

ggmap(map, extent = "device", ylab = "lat", xlab = "lon") + 
    geom_segment(data = geo, aes(y = lat, x = lon, yend = latend, xend = lonend)) 

同时删除geo$,为了显示一个箭头只是增加arrow = arrow()geom_segment

ggmap(map, extent = "device", ylab = "lat", xlab = "lon") + 
    geom_segment(data = geo, aes(y = lat, x = lon, yend = latend, xend = lonend), 
       arrow = arrow()) 
+0

谢谢!我尝试添加:'eom_segment(data = geo,arrow(y = lat,x = lon,yend = latend,xend = lonend))' 但它似乎不起作用:( – MikeR

+0

@MikeR请参阅我编辑的答案,现在应该清楚:) – beetroot

+0

谢谢你!现在即时获得一个箭头,这是最重要的部分。 如果我想让箭头从第一个目的地移到另一个目的地,我该怎么办? 可以说我以下数据添加到我的地理数据集: 'secondrow = C(11.10557,60.18959,12.10557,62.18959,999) 地理< - rbind(GEO,secondrow)' 好像它不创建默认附加箭头 - 我需要在geom_segment中更改哪些内容? – MikeR