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

如何使用sf包绘制半径随要素属性N变化的圆形?

实现按属性值比例设置点半径的方法

问题背景

我有一组包含地图坐标及对应数值的数据:

require(tidyverse)

df <- tribble(     ~ x,      ~ y,   ~ N,
               776025., 6990858.,   100,
               744220 , 6940666.,    75,
               774222., 6904024.,    55,
               719368., 6973708.,    30,
               735330., 7029420.,     1)

已通过sf包将坐标转换为几何要素并生成sf对象:

require(sf)
(geom_column <- st_sfc(pmap(df[, 1:2], function(x, y) st_point(c(x, y)))))
(df <- st_sf(df[, 3], geometry = geom_column))

默认的plot(df)会生成按N值区分颜色的点图,现在需要替换为半径与N属性成比例的圆形。


解决方案

方法1:基础绘图(base plot)控制大小

利用plot()的cex参数直接关联N值,可通过缩放因子调整点的整体大小:

# 简单缩放:直接用N乘以缩放系数
scale_factor <- 0.04  # 可根据可视化效果调整
plot(df$geometry, pch = 21, bg = "#2ecc71", cex = df$N * scale_factor)

如果需要更精准的大小范围控制,可对N做线性归一化:

# 自定义最大/最小点尺寸
max_size <- 6
min_size <- 0.8
# 线性缩放N值到设定的尺寸范围
scaled_size <- (df$N - min(df$N)) / (max(df$N) - min(df$N)) * (max_size - min_size) + min_size

plot(df$geometry, pch = 21, bg = "#3498db", cex = scaled_size, lwd = 1)
  • pch=21是带填充色的圆形,可通过bg设置填充色,lwd调整边框粗细

方法2:ggplot2(推荐,更灵活)

结合ggplot2与sf的原生支持,能更直观地控制图形样式:

library(ggplot2)

ggplot(df) +
  geom_sf(aes(size = N), 
          shape = 21,       # 带填充的圆形
          fill = "#e74c3c", # 填充色
          color = "black") + # 边框色
  scale_size_continuous(range = c(1, 7)) + # 自定义尺寸范围
  theme_minimal()
  • aes(size = N)直接将点的大小与N绑定
  • scale_size_continuous可灵活调整点的最大、最小尺寸,避免视觉失衡

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:31:11