You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot生成地图与shapefile矢量图层叠加操作问题咨询

解决方法

你当前的问题核心是仅读取了shp矢量文件,并未将其作为图层加入ggplot的绘图调用中,同时需要保证两个图层坐标系一致才能正确对齐叠加,具体调整步骤如下:

1. 预处理矢量数据,统一坐标系

首先将读取的shp对象转换为ggplot支持的sf格式,并和你的趋势数据tx_trend统一坐标系,默认经纬度数据使用WGS84(EPSG:4326):

# 加载所需包
library(sf)
library(dplyr)

# 将sp格式的shp转为sf格式,并统一坐标系为WGS84
# 如果你的tx_trend经纬度是其他坐标系,把4326替换为对应EPSG编码即可
data.shape_sf <- st_as_sf(data.shape) %>% 
  st_transform(crs = 4326)

2. 调整ggplot代码,添加矢量边界图层

将矢量图层加在热力图图层之后,设置填充透明避免遮挡下层的趋势热力图:

ggplot()+
  # 底层:趋势热力图
  geom_tile(data = tx_trend, aes(x = longitude, y = latitude, fill = slope))+
  scale_fill_gradientn(colors = rev(pals::linearlhot(100)), name = "ºC/10y", limits = c(0.1,0.5)) +
  # 显著性标记点
  geom_point(data = filter(tx_trend, sign < 0.01),aes(x = longitude, y = latitude, color = "Sign. trend \n p-value <0.01"),
                        size = 0.7, show.legend = T) +
  # 新增:shp矢量边界图层,fill=NA表示透明填充只显示边界
  geom_sf(data = data.shape_sf, fill = NA, color = "black", linewidth = 0.3)+
  scale_color_manual(values = c("black"), name = "")+
  coord_sf()+ # 替换原coord_fixed适配sf图层的坐标系,也可保留coord_fixed按需调整
  xlab("Longitude") + ylab("Latitude")+
  labs(title = "Decadal trend Summer", 
       subtitle = "(1981-2016)",
       caption = "")+
  theme_bw() +
  guides(fill = guide_colourbar(barwidth = 9, barheight = 0.5, title.position="right"))+
  theme(legend.position = "bottom")

注意事项

  • 如果叠加后边界和热力图位置不匹配,可先运行st_crs(data.shape_sf)查看shp原始坐标系,确认和tx_trend的经纬度坐标系一致后再转换
  • 若使用旧版本ggplot不支持geom_sf,可将shp用fortify(data.shape)转为数据框后,用geom_polygon绘制边界,对应需要映射x=long、y=lat、group=group参数

内容的提问来源于stack exchange,提问作者Juan Carlos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:57:03