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

使用stat_sf_coordinates绘图时如何添加散点图例?

问题

使用ggplot和sf制作分级统计图叠加散点的地图时,分级统计图的图例正常显示,但通过stat_sf_coordinates渲染的散点无法显示图例。尝试设置show.legend = "geometry"也无效,散点图例始终被分级统计图的设置覆盖,请问如何为散点添加第二个图例?

代码如下:

ggplot(final.OD.2024) +
  geom_sf(data = OD.deaths.map, aes(fill = all.drug.death.rate, geometry = geometry), colour = "white") + 
  stat_sf_coordinates(aes(geometry = geometry), color = "red", size = 0.9, position = position_jitter(), show.legend = "geometry") + 
  theme(panel.background = element_rect(fill = "white"),
        plot.title = element_text(size = 20, hjust = 0.5),
        axis.ticks = element_blank(),
        axis.text = element_blank()) + 
  scale_fill_gradient2(low = "white", high='darkblue') + 
  xlab(element_blank()) +
  ylab(element_blank()) +
  guides(fill = guide_colorbar(title = "All Drug Overdose Death Rate \n (Deaths per 100,000 Pop.)")) + 
  theme(legend.justification = "center")
解决方法

问题核心在于:你直接将color设为常量值,没有绑定到aes()映射中,ggplot不会为非映射的常量属性生成图例。要生成散点图例,需要把颜色属性纳入aes(),再通过手动颜色标度定义样式。

具体修改步骤:

  • 将color = "red"移入aes()内部,同时定义一个图例标签(比如color = "散点标记")
  • 添加scale_color_manual()指定颜色对应关系,并设置图例标题
  • 调整show.legend参数为"point",适配stat_sf_coordinates输出的点类型

修改后的完整代码:

ggplot(final.OD.2024) +
  geom_sf(data = OD.deaths.map, aes(fill = all.drug.death.rate, geometry = geometry), colour = "white") + 
  # 将color纳入aes映射,定义图例标签
  stat_sf_coordinates(aes(geometry = geometry, color = "散点标记"), size = 0.9, position = position_jitter(), show.legend = "point") + 
  theme(panel.background = element_rect(fill = "white"),
        plot.title = element_text(size = 20, hjust = 0.5),
        axis.ticks = element_blank(),
        axis.text = element_blank()) + 
  scale_fill_gradient2(low = "white", high='darkblue') + 
  # 手动设置散点颜色与图例标题
  scale_color_manual(values = "red", name = "散点含义说明") +
  xlab(element_blank()) +
  ylab(element_blank()) +
  guides(
    fill = guide_colorbar(title = "All Drug Overdose Death Rate \n (Deaths per 100,000 Pop.)"),
    # 可选:调整散点图例样式,比如标题位置
    color = guide_legend(title.position = "top")
  ) + 
  theme(legend.justification = "center")

补充说明:

  • 把颜色放入aes()后,ggplot会将其识别为需要生成图例的映射关系
  • show.legend = "point"是因为stat_sf_coordinates本质是把sf对象转换为点坐标输出,用"point"才能正确触发图例渲染
  • 若需要自定义图例的位置、排序等,可在guides()中进一步配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:56:12