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

如何为ggplot2双层地图(国界+网格)添加自定义双项图例

解决ggplot2地图双项图例问题

要实现包含国界和网格单元的双项图例,核心是通过手动映射图例变量并自定义图例样式,避免直接将样式参数写在aes()外导致无法生成图例。以下是修正后的代码及说明:

完整代码

ggplot() +
  # 国界图层:将图例项映射到aes中
  geom_sf(data = country, 
          aes(fill = "Country border", color = "Country border"),
          size = 1) +
  # 网格图层:将图例项映射到aes中
  geom_sf(data = grid, 
          aes(color = "Grid border"),
          fill = NA) +
  # 手动指定填充色,统一图例名称为"Legend"
  scale_fill_manual(name = "Legend",
                    values = c("Country border" = "white")) +
  # 手动指定线条颜色
  scale_color_manual(name = "Legend",
                     values = c("Country border" = "black",
                                "Grid border" = "black")) +
  # 手动指定线条粗细
  scale_size_manual(name = "Legend",
                    values = c("Country border" = 1,
                               "Grid border" = 0.3)) +
  # 合并图例并修正显示样式
  guides(
    fill = guide_legend(order = 1,
                        override.aes = list(color = "black", size = 1)),
    color = guide_legend(order = 1,
                         override.aes = list(fill = c("white", NA),
                                            size = c(1, 0.3)))
  )

关键说明

  1. 映射图例变量:将"Country border"和"Grid border"作为映射变量放在aes()内,让ggplot识别需要生成对应的图例条目,而不是把样式参数直接写在图层外。
  2. 统一图例名称:所有scale_*_manual的name参数设为"Legend",确保填充和线条的图例合并为一个。
  3. 修正图例样式:通过guides()里的override.aes强制调整图例的显示效果:
    • 让"Country border"显示白色填充+黑色粗线
    • 让"Grid border"显示黑色细线(无填充)
  4. 调整细节:可以修改scale_size_manual里的数值,适配你需要的网格线条粗细。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:11:00