如何基于rnaturalearth与sf对象添加城市点及带色值的连接线?
解决方案
要实现你的需求,我们可以基于ggplot2配合rnaturalearth完成,核心步骤是准备城市坐标数据、构建连接线的起点/终点坐标集,然后通过颜色映射关联F值,同时匹配目标颜色比例尺。以下是完整代码及关键说明:
1. 加载依赖包
首先确保安装并加载所需工具包:
# 安装(首次运行) # install.packages(c("rnaturalearth", "rnaturalearthdata", "ggplot2", "dplyr")) library(rnaturalearth) library(rnaturalearthdata) library(ggplot2) library(dplyr)
2. 准备基础地图数据
使用ne_countries获取世界地图的SF格式数据(兼容ggplot的空间绘图):
world <- ne_countries(scale = "medium", returnclass = "sf")
3. 定义城市与连接线数据
假设你有三座目标城市,以及每对城市间的F值(替换为你的实际数据即可):
# 城市坐标数据:替换为你的目标城市经纬度 cities <- data.frame( city = c("Beijing", "Washington DC", "London"), lon = c(116.4074, -77.0369, -0.1278), lat = c(39.9042, 38.9072, 51.5074) ) # 连接线数据:每一行代表一对城市的连接及对应的F值 connections <- data.frame( from_city = c("Beijing", "Beijing", "Washington DC"), to_city = c("Washington DC", "London", "London"), F_value = c(0.75, 0.62, 0.88) # 替换为你的实际F值 ) # 匹配连接线的起点/终点坐标 connections <- connections %>% left_join(cities, by = c("from_city" = "city")) %>% rename(start_lon = lon, start_lat = lat) %>% left_join(cities, by = c("to_city" = "city")) %>% rename(end_lon = lon, end_lat = lat)
4. 绘制地图(含点与彩色连接线)
关键细节:
- 用
geom_sf绘制基础地图 - 用
geom_segment绘制城市间的连接线,通过color = F_value映射颜色 - 用
geom_point标记城市位置,可调整样式 - 用
scale_color_*系列函数匹配你需要的颜色比例尺
ggplot() + # 绘制世界地图底图 geom_sf(data = world, fill = "antiquewhite", color = "gray50") + # 绘制城市间彩色连接线 geom_segment( data = connections, aes(x = start_lon, y = start_lat, xend = end_lon, yend = end_lat, color = F_value), linewidth = 1.5, # 线条粗细可调整 alpha = 0.8 # 透明度可调整 ) + # 绘制城市标记点 geom_point( data = cities, aes(x = lon, y = lat), color = "darkred", size = 3, shape = 19 ) + # 匹配目标颜色比例尺(示例用viridis渐变,替换为你需要的配色) scale_color_viridis_c( name = "紧密程度(F值)", # 图例名称 option = "plasma" # viridis系列配色,可选"viridis"/"magma"/"inferno"/"plasma"/"cividis" # 若示例是自定义渐变,替换为: # scale_color_gradient(low = "lightblue", high = "darkred", name = "紧密程度(F值)") ) + # 可选:调整地图范围聚焦目标区域 coord_sf(xlim = c(-120, 150), ylim = c(20, 70), expand = FALSE) + # 主题调整 theme_minimal() + labs(title = "城市间紧密程度地图", x = "", y = "") + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), legend.position = "bottom" )
关键调整说明
- 若你的示例图使用特定颜色比例尺,直接替换
scale_color_*函数即可:比如示例是从浅绿到深绿,就用scale_color_gradient(low = "#e5f5e0", high = "#238b45") - 城市坐标和F值替换为你的实际数据即可
- 若需要绘制更多城市间的连接,只需扩展
connections数据框的行即可
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

