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

在ggplot2中实现Shapefile累积式绘图的技术问询

实现累积式年份分面绘图(叠加Shapefile)

问题描述

我有一个包含年份列("Jahr")的Shapefile,需要将其叠加在名为"africa"的Shapefile上绘图。当前代码会为每个年份生成独立图表,但我需要实现累积式绘图——比如1980年的图表要显示1950年以来的所有图形。

原代码:

library(sf)
library(giscoR)
library(ggplot2) # 补充原代码遗漏的绘图包

africa <- gisco_get_countries(region = "Africa", resolution = 60, level = 1) %>%
  st_union() %>%
  st_transform(3857)

sample <- st_sample(africa, 40)
sample <- st_as_sf(sample)
sample$Jahr <- floor(runif(41, min=1950, max=1980))


ggplot(africa)+
  geom_sf()+
  geom_sf(data = sample, aes(col = "Jahr"))+
  facet_wrap( "Jahr")

解决方案

要实现累积式分面,核心是为每个分面年份生成包含该年份及之前所有年份的数据集。以下是修改后的完整代码及说明:

完整代码

library(sf)
library(giscoR)
library(ggplot2)
library(dplyr)
library(purrr)

# 生成非洲底图
africa <- gisco_get_countries(region = "Africa", resolution = 60, level = 1) %>%
  st_union() %>%
  st_transform(3857)

# 生成带年份的样本数据(修正行数不匹配问题)
set.seed(123) # 设置随机种子保证结果可复现
sample <- st_sample(africa, 40) %>%
  st_as_sf() %>%
  mutate(Jahr = floor(runif(n(), min=1950, max=1980)))

# 生成累积式数据集:每个分面年份对应所有≤该年份的点
unique_years <- sort(unique(sample$Jahr))
cumulative_sample <- map_dfr(unique_years, function(year) {
  sample %>%
    filter(Jahr <= year) %>%
    mutate(Facet_Jahr = year) # 添加分面用的年份标记
})

# 绘制累积式分面图
ggplot(africa) +
  geom_sf(fill = "lightgray", color = "white") + # 优化底图样式
  geom_sf(data = cumulative_sample, aes(color = factor(Jahr)), size = 2) +
  facet_wrap(~Facet_Jahr) +
  scale_color_discrete(name = "年份") +
  labs(title = "非洲地区累积年份点分布", x = NULL, y = NULL) +
  theme_minimal()

关键逻辑说明

  • 累积数据集生成:用map_dfr遍历每个唯一年份,筛选出所有早于等于当前年份的样本数据,并用Facet_Jahr标记该分面对应的年份,最后合并为一个完整数据框
  • 累积筛选:filter(Jahr <= year)是实现累积效果的核心,确保每个分面包含历史所有数据
  • 可视化优化:通过factor(Jahr)映射颜色,可直观区分不同年份的点;也可根据需求将颜色设为统一值,仅保留累积展示逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:55:10