使用sf与ggplot绘制美国州地图时点位显示异常,请求修复code1
问题描述
我有如下经纬度点数据:
set.seed(123) # 保证结果可复现 Latitude = sample(31:46, size = 300, replace = TRUE) Longitude = sample(-80:-120, size = 300, replace = TRUE) df = data.frame(Latitude, Longitude)
我用以下代码(code1)绘图时,点位无法正确显示:
code1
library(sf) library(tidyverse) usa <- st_as_sf(maps::map("state", fill=TRUE, plot =FALSE)) ggplot(usa) + geom_sf(color = "#2b2b2b", fill = "royalblue", size=0.125) + coord_sf(crs = st_crs("+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"), datum = NA)+ geom_point(data = df, aes(x = Longitude, y = Latitude))
虽然我能用code2完成绘图,但需要code1那种带曲线投影的地图效果,请求修复code1:
code2
world <- ne_countries(scale = "medium", returnclass = "sf") ggplot(data = world) + geom_sf() + coord_sf(xlim = c(-67.74, -125.55), ylim = c(25, 50), expand = FALSE)+geom_point(data = df, aes(x = Longitude, y = Latitude))
修复方案
问题根源:code1里直接用geom_point传入普通数据框的经纬度,这些坐标是WGS84(EPSG:4326)的原始经纬度,没有转换为地图使用的LAEA投影坐标系,导致点位和地图错位。
修复代码如下:
library(sf) library(tidyverse) set.seed(123) # 保证结果可复现 Latitude = sample(31:46, size = 300, replace = TRUE) Longitude = sample(-80:-120, size = 300, replace = TRUE) df = data.frame(Latitude, Longitude) # 将点数据转为sf对象,明确原始坐标的CRS为WGS84 df_sf <- st_as_sf(df, coords = c("Longitude", "Latitude"), crs = 4326) usa <- st_as_sf(maps::map("state", fill=TRUE, plot =FALSE)) # 定义目标投影坐标系 target_crs <- st_crs("+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs") ggplot(usa) + geom_sf(color = "#2b2b2b", fill = "royalblue", size=0.125) + coord_sf(crs = target_crs, datum = NA) + # 用geom_sf绘制点,自动匹配地图投影 geom_sf(data = df_sf, color = "red", size = 1)
说明
- 把普通数据框
df转为sf对象时,通过crs = 4326声明原始坐标是国际通用的WGS84经纬度 - 使用
geom_sf绘制点,ggplot会自动根据coord_sf设置的投影转换坐标,确保点位和地图完全匹配 - 可以自行调整点的
color、size参数优化显示效果
内容的提问来源于stack exchange,提问作者Ali Roghani
相关产品推荐
相关产品推荐

