gpt4 book ai didi

r - 如何在 ggplot map 上添加地理空间连接?

转载 作者:行者123 更新时间:2023-12-05 01:48:26 24 4
gpt4 key购买 nike

使用 this作为引用,我正在尝试绘制下 48 州的 map 并添加图层以可视化各州之间的流动。

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')

但是为第二个列表元素添加另一层会破坏它,但这是我对 R 和 ggplot 的有限了解所能得到的!

最佳答案

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')
}

关于r - 如何在 ggplot map 上添加地理空间连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11813299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com