如何使用ggmap在R中的地图上绘制箭头

时间:2016-07-25 12:29:10

标签: r google-maps plot 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 个答案:

答案 0 :(得分:1)

您的细分未被绘制,因为您混淆了纬度和经度,x对应于经度,y对应于纬度。此外,您应该使用data = geo并从geo$

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

此外,为了显示箭头,只需将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())