繁体   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