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

如何在ggplot中叠加法国地图背景与六边形统计图层?

解决方法

你不能直接将两个ggplot对象叠加(p + bck这种写法无效),正确的做法是在同一个绘图流程中依次添加背景图层和六边形图层,注意图层顺序:先绘制地图背景,再绘制六边形热力图,这样六边形会覆盖在背景之上。

修改后的完整代码如下:

## Extract data
temp <- tempfile()
download.file("https://inventaire-forestier.ign.fr/dataifn/data/export_dataifn_2005_2022.zip",temp)
couvert <- read.csv(unz(temp, "COUVERT.csv"), sep=";")
placette <- read.csv(unz(temp, "PLACETTE.csv"), sep=";")
espar <- read.csv(unz(temp,"espar-cdref13.csv"), sep=";")
unlink(temp)

## e.g. for Abies alba
ID <- espar$X...espar[espar$lib_cdref=="Abies alba"]
couvert_sp <- couvert[couvert$ESPAR_C == ID ,]
df <- merge(placette[ , c("IDP", "XL", "YL")], couvert_sp, by="IDP", all.y=T)

# coordinates conversion (required)
crs193 <- "+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +units=m +no_defs"
wgs84 <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"

xyl93 <- df[, c("XL", "YL", "IDP")]
require(sp)
coordinates(xyl93) <- ~ XL + YL
proj4string(xyl93) <- CRS(crs193)
xyl <- as.data.frame(spTransform(xyl93, wgs84))

require(dplyr)
df2 <- merge(xyl, df, by="IDP", all.x=T, all.y=T) %>% distinct(IDP, .keep_all = TRUE)

# graphic
require(ggplot2)
AB <- map_data("world") %>% filter(region %in% "France")

require(paletteer)
# 合并背景与六边形图层,注意顺序:先背景,再六边形
p <- ggplot() +
  # 法国地图背景
  geom_polygon(data = AB, aes(x=long, y = lat, group = group), fill="#ECECEC", color="white") +
  # 六边形热力图
  stat_summary_hex(data = df2, aes(x=coords.x1, y=coords.x2, z=TCA), fun = mean, bins = 80) +
  scale_fill_gradientn(colours = paletteer_c("ggthemes::Classic Green", 30)) +
  theme_void() +
  coord_map() 

p

关键说明

  1. 图层顺序:geom_polygon(背景)必须放在stat_summary_hex之前,因为ggplot会按代码顺序绘制图层,后绘制的图层会覆盖在先绘制的图层上。
  2. 统一坐标系:确保所有图层使用相同的坐标系(这里用coord_map()),避免出现错位或显示异常。
  3. 避免独立ggplot对象:不要分开创建两个独立的ggplot对象再尝试相加,而是在同一个ggplot()起始调用下添加所有需要的图层。

如果需要调整地图的显示范围(比如只聚焦法国本土),可以在coord_map()中添加xlim和ylim参数,例如:

coord_map(xlim = c(-5, 10), ylim = c(41, 52))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:13:20