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

如何使用geom_sf调整图例与地图间距,避免图例覆盖地图

解决ggplot + geom_sf地图图例覆盖问题

你的问题核心是plot.margin仅调整整个图表的外围边距,不会改变绘图面板(地图区域)与图例的内部布局关系。要解决图例覆盖地图的问题,可从以下几个方向调整:

方法1:将图例移至绘图面板外,配合调整底部边距

直接把图例的y轴位置设为负数(超出绘图面板范围),同时加大底部外边距保证图例完整显示:

  • 修改legend.position为负数y值(比如c(0.5, -0.06),数值可根据实际效果微调)
  • 给plot.margin添加明确单位(默认单位是lines,数值2的高度往往不够)
  • 开启coord_sf(clip = "off"),允许元素超出绘图面板显示,避免图例被裁剪

修改后的完整代码示例:

ggplot(shp_dados_ce) +
  geom_sf(aes(fill = populacao_2022)) +
  coord_sf(clip = "off") + # 新增:允许元素超出面板显示
  theme_void() +
  scale_fill_viridis(
    trans = "log10",
    name="Habitantes",
    guide = guide_legend( 
      keyheight = 0.25,
      keywidth= 1,
      label.position = "bottom",
      title.position = 'top',
      nrow=1
    ) 
  ) +
  labs(
    title = "title",
    subtitle = "subtitle",
    caption = "caption"
  ) +
  theme(
    text = element_text(color = "#22211d"),
    panel.background = element_rect(fill = "#f5f5f2", color = NA),
    panel.border = element_rect(fill = NA, color = "green"),
    
    plot.background = element_rect(fill = "#f5f5f2", color = NA),
    plot.margin = margin(b = 30, unit = "pt"), # 调整:添加单位并增大底部边距
    plot.title = element_text(
      size= 16,
      hjust=0.05,
      vjust=0.05,
      color = "#4e4d47"
    ),
    plot.subtitle = element_text(
      size= 11,
      hjust=0.05,
      color = "#4e4d47",
      margin = margin(
        b = -0.25,
        t = 5
      )
    ),
    
    legend.background = element_rect(fill = "green", color = NA),
    legend.box.background = element_rect(color = "black"),
    legend.position = c(0.5, -0.06), # 调整:将图例下移至面板外
    legend.text = element_text(size = 6),
    legend.title = element_text(size = 6),
    legend.margin = margin(l = 0.5 ,t = 2),
    legend.box.margin = margin(3,2,2,2)
  )

方法2:缩小绘图面板,给图例腾出内部空间

如果不想把图例移到面板外,可通过给绘图面板添加内边距缩小地图区域:
在theme()中添加panel.margin = margin(b = 20, unit = "pt")(注意:ggplot2新版本中panel.margin可能被panel.spacing替代,需根据版本调整)。不过这种方法会压缩地图显示空间,更推荐方法1。

关键注意事项

  • margin()函数必须明确指定单位(如pt/cm),默认的lines单位高度通常不足以容纳图例
  • coord_sf(clip = "off")是让移出面板的图例正常显示的必要设置,否则会被系统自动裁剪

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:24:56