簡體   English   中英

用ggplot2 / ggmap在R中的地圖上繪制線

[英]Plotting lines over maps in R with ggplot2/ggmap

我正在嘗試在R中創建一個地圖,該地圖在ggmap區域的Google Maps圖像上覆蓋一個人工地理邊界(由一組(x,y)點的w / lat和lon值確定)。 我正在使用的代碼如下。

ggmap(mapgilbert) +
  geom_point(data = df, aes(x = lon, y = lat, fill = "red", alpha = 0.8), size = 1, shape = 21) +
  guides(fill=FALSE, alpha=FALSE, size=FALSE) +
  for (i in 1:3){
      geom_segment(data = coords, aes(x = lon[[i]], y = lat[[i]], xend = lon[[(i+1)]], yend = lat[[(i+1)]], alpha = 0.8))
  }

注意,coords是一個包含相關緯度和經度值的data.frame,而df是一個包含點值的相似data.frame; 它們的結構都正確。

只需一次迭代,上述代碼即可正常工作; 出現區域圖,出現我要繪制的三個點,並且在它們之間繪制的線也出現了。 但是,當我嘗試在for循環中迭代執行此操作時,沒有任何行顯示。 我在類似的帖子中讀到,這是因為R的自動打印功能在循環中不起作用,所以我嘗試將相關語句包裝在print()函數中,但是由於某種原因,它僅返回“ NULL”。 我感覺自己犯了一些顯而易見的錯誤,但不確定是什么。 先感謝您!

由於沒有可復制的數據,因此我創建了一個隨機數據。 請從下一次提供您的數據。 對於所有SO用戶,當他們尋求幫助時,這是必要的。

您需要為geom_segment創建一個數據框。 您根本不必遍歷數據。 mydf每一行都是一行。 您可以分別使用xyxendyend為經度和緯度指定兩個點。

library(ggmap)
library(ggplot2)

# Create a data frame for segments.
mydf <- data.frame(id = 1:3, 
                   lat_1 = c(37.78, 37.75, 37.73), 
                   lon_1 = c(-122.41, -122.40, -122.405), 
                   lat_2 = c(37.77, 37.75, 37.72), 
                   lon_2 = c(-122.43, -122.42, -122.415))

# Create randam data points.
set.seed(111)

mydf2 <- data.frame(lon = runif(n = 100, min = -122.49, max = -122.38),
                    lat = runif(n = 100, min = 37.69, max = 37.813))

# Get a map 
map <- get_map(location = c(left = -122.523, bottom = 37.69,
                            right = -122.35, top = 37.8),
               maptype = "roadmap", source = "google", color = "bw")

# Plot the points and draw the segments on the map. 
ggmap(map) + 
geom_point(data = mydf2, 
           aes(x = lon, y = lat), color = "red", alpha = 0.6, size = 2) + 
geom_segment(data = mydf, 
             aes(x = lon_1, y = lat_1, xend = lon_2, yend = lat_2), 
             color = "green", size = 2, alpha = 0.8, lineend = "round")
#> Warning: Removed 34 rows containing missing values (geom_point).

reprex軟件包 (v0.2.0)創建於2018-03-25。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM