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

绘制sf对象时图例与scale_size_area不匹配问题

问题描述

我有三个采用同一投影(EPSG:3005)的sf格式空间图层:两个线图层和一个点图层。我希望点的面积与其数值成比例,但点图层(数据框名为x)的图例无法匹配绘图效果——图例显示单一大小的方形符号,而绘图中是按比例变化的圆点。我尝试了以下两段代码,包括覆盖图例美学设置,但问题仍未解决,怀疑是否与sf对象的绘图机制有关。

尝试的代码1

ggplot() +
  geom_sf(data = track, color = "orange", lwd = 1.4) +          # line
  geom_sf(data = SZ_cropped, color = "grey40", lwd = 0.5) +     # line
  geom_sf(aes(size = total), data = x, color = "black", alpha = 0.7, shape = 21, fill = "purple") +      # dots
  scale_size_area(name = "Count") +                              # proportional area dots

尝试的代码2

ggplot() +
  geom_sf(data = track, color = "orange", lwd = 1.4) +          # line
  geom_sf(data = SZ_cropped, color = "grey40", lwd = 0.5) +     # line        
  geom_sf(aes(size = total), data = x, color = "black", alpha = 0.7, shape = 21, fill = "purple") +      # dots
  scale_size_area(name = "Count", max_size = 5) + # proportional area dots
  guides(size = guide_legend(override.aes = list(shape = 21, fill = "purple", color = "black"))) 
解决方法

问题出在geom_sf的图例渲染逻辑,默认会采用空间对象的符号系统,导致手动设置的shape等参数在图例中未生效。以下两种方法可以解决:

方法1:指定key_glyph参数

在geom_sf中添加key_glyph = "point",强制图例使用点型符号,覆盖sf默认的符号渲染:

ggplot() +
  geom_sf(data = track, color = "orange", lwd = 1.4) +          # 线图层1
  geom_sf(data = SZ_cropped, color = "grey40", lwd = 0.5) +     # 线图层2
  geom_sf(aes(size = total), data = x, color = "black", alpha = 0.7, shape = 21, fill = "purple",
          key_glyph = "point") +      # 关键:指定图例符号类型为点
  scale_size_area(name = "Count", max_size = 5) + 
  guides(size = guide_legend(override.aes = list(shape = 21, fill = "purple", color = "black")))

方法2:改用geom_point配合坐标提取

提取点图层的坐标后用普通geom_point绘制,绕开sf图例的特殊逻辑,更灵活控制图例:

# 提取点的坐标信息
x_coords <- st_coordinates(x)
x_df <- cbind(x, x_coords)

ggplot() +
  geom_sf(data = track, color = "orange", lwd = 1.4) +
  geom_sf(data = SZ_cropped, color = "grey40", lwd = 0.5) +
  geom_point(aes(X, Y, size = total), data = x_df, color = "black", alpha = 0.7, shape = 21, fill = "purple") +
  scale_size_area(name = "Count", max_size = 5)
补充说明
  • scale_size_area已经保证点的面积与total数值成比例,max_size可根据可视化需求调整最大点的尺寸
  • 方法1更贴合sf对象的使用场景,方法2适合需要对图例进行更精细定制的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:18:13