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

如何在ggplot2中为巴西区域地图添加调查百分比标注?

解决巴西区域地图百分比标注问题

问题背景

已通过ne_states获取巴西州级地图数据并划分为5个区域(Sul、Sudeste、Centro-Oeste、Norte、Nordeste),同时拥有各区域参与者占比的调查数据,但使用ggplot2绘图时,无法将百分比正确标注在对应区域上。

原代码的核心问题

  1. 数据关联错误:regionsBR是包含每个州的sf对象,直接full_join会导致regionsJoined中每个州对应一条调查数据,出现大量重复值
  2. 文本定位错误:geom_text中使用x = prop和y = prop,用百分比数值作为坐标,完全不符合地图的经纬度定位逻辑
  3. 图层逻辑冗余:同时绘制底图BRA和区域图层regionsBR,造成视觉重叠

修正后的完整代码

1. 加载依赖包并处理地图数据

library(rnaturalearth)
library(rnaturalearthhires)
library(stringr)
library(dplyr)
library(sf)
library(ggplot2)

# 获取巴西州级地图数据
BRA <- ne_states(country = "Brazil", returnclass = "sf") 

# 按区域分组州,合并区域几何并计算中心坐标
regionsBR <- BRA %>%
  mutate(postal = factor(postal),
         Q8 = fct_collapse(postal, 
                           'Sul' = c('RS', 'SC', 'PR'),
                           'Sudeste' = c('RJ', 'SP', 'MG', 'ES'),
                           'Centro-Oeste' = c('MS', 'MT', 'GO', 'DF'),
                           'Norte' = c('RO', 'AC', 'AM', 'RR', 'PA', 'TO', 'AP'),
                           'Nordeste' = c('BA', 'PI', 'MA', 'CE', 'SE', 'AL', 'PE', 'PB', 'RN'))) %>% 
  group_by(Q8) %>%
  summarise(geometry = st_union(geometry)) %>% # 合并区域内所有州为单个多边形
  mutate(centroid = st_centroid(geometry), # 计算区域几何中心
         lon = st_coordinates(centroid)[,1], # 提取中心经度
         lat = st_coordinates(centroid)[,2]) # 提取中心纬度

2. 关联调查数据

# 调查数据结构
regionsQuest <- structure(list(Q8 = structure(1:5, .Label = c("Norte", "Nordeste", 
"Sudeste", "Centro-Oeste", "Sul"), class = "factor"), n = c(4L, 
5L, 8L, 14L, 16L), prop = c(8.51, 10.64, 17.02, 29.79, 34.04), 
    sd = c(0.11, 0.11, 0.11, 0.11, 0.11)), row.names = c(NA, 
-5L), class = "data.frame")

# 关联地图数据与调查数据(每个区域仅保留一条记录)
regionsJoined <- regionsBR %>% 
  left_join(regionsQuest, by = "Q8")

3. 绘制带正确标注的地图

ggplot() + 
  geom_sf(data = regionsJoined, aes(fill = Q8), color = "black") + # 绘制区域填充层
  geom_text(data = regionsJoined, 
            aes(x = lon, y = lat, 
                label = str_glue('{round(prop, 1)} %')), # 格式化百分比文本
            size = 4, fontface = "bold") +
  theme_light() +
  labs(fill = "巴西区域") +
  theme(legend.position = "bottom")

关键修正说明

  • 合并区域几何:通过group_by(Q8) %>% summarise(st_union(geometry))将每个区域的多个州合并为单个多边形,避免数据重复
  • 计算中心坐标:用st_centroid获取每个区域的几何中心,提取经纬度作为文本标注的定位坐标
  • 正确关联数据:使用left_join确保每个区域仅对应一条调查数据,避免冗余
  • 修正文本定位:用真实的经纬度lon和lat替代错误的百分比数值,确保标注出现在对应区域中心

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:12:04