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

R绘制按相对大小排列、自定义着色的国家多边形图表求助

R语言绘制非地理坐标缩放国家多边形图表解决方案

核心实现逻辑

  • 放弃原始地理坐标体系,对每个国家多边形做标准化处理
  • 按计算得到的t$rs值对标准化后的多边形做等比例缩放
  • 将缩放后的多边形平移到预设网格点位,实现相邻摆放无重叠
  • 填充色直接绑定t$value正负属性,正值为绿、负值为红

完整可运行代码

library(dplyr)
library(sf) 
library(ggplot2)

# 自定义数据集
t <- data.frame(id    = c(136,142,172,567),
                name  = c("Italy","Norway","Finland","Singapore"),
                value = c(-0.921253632,245.6713064,4.049413648,207.5896534))
# 计算绝对值最小值(避免和内置函数min重名,改用min_abs)
min_abs <- min(abs(t$value))
# 计算相对值rs
t$rs <- abs(t$value) / min_abs

# 读取国家shape文件,替换原已弃用的readOGR方法
unzip("World_Countries_(Generalized).zip", exdir = ".")
countries <- st_read("World_Countries__Generalized_.shp") %>% 
  filter(COUNTRY %in% t$name) %>% 
  # 关联业务数据
  left_join(t, by = c("COUNTRY" = "name"))

# 预设网格点位,4个国家排成2*2布局,间距3避免缩放后重叠
grid_pos <- data.frame(
  COUNTRY = c("Italy","Norway","Finland","Singapore"),
  target_x = c(0, 3, 0, 3),
  target_y = c(0, 0, 3, 3)
)
countries <- countries %>% left_join(grid_pos, by = "COUNTRY")

# 自定义几何处理函数:归一化→按rs缩放→平移到目标点位
process_geom <- function(geom, rs, tx, ty) {
  # 1. 平移到质心在原点
  cent <- st_centroid(geom)
  geom_trans <- geom - cent
  # 2. 归一化到单位尺寸
  bbox <- st_bbox(geom_trans)
  scale <- max(bbox$xmax - bbox$xmin, bbox$ymax - bbox$ymin)
  geom_norm <- geom_trans / scale
  # 3. 按rs值缩放,乘以0.8的系数避免边缘重叠
  geom_scale <- geom_norm * rs * 0.8
  # 4. 平移到目标网格点位
  geom_final <- geom_scale + c(tx, ty)
  return(geom_final)
}

# 批量处理所有国家的几何
countries$geometry <- mapply(process_geom, 
                             countries$geometry, 
                             countries$rs, 
                             countries$target_x, 
                             countries$target_y) %>% 
  st_sfc(crs = st_crs(countries))

# 绘图
ggplot(countries) +
  geom_sf(aes(fill = value > 0), color = "white", linewidth = 0.3) +
  # 填充色设置:正值绿,负值红
  scale_fill_manual(values = c("TRUE" = "#27ae60", "FALSE" = "#e74c3c"),
                    labels = c("正值", "负值"),
                    name = "数值属性") +
  # 标注国家名称
  geom_sf_text(aes(label = COUNTRY), size = 3, color = "black") +
  # 隐藏坐标轴等多余元素
  theme_void()

调整说明

如果需要修改布局间距、缩放比例,直接调整grid_pos的坐标参数、缩放系数即可适配不同的展示需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:27:03