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

如何移除geom_sf绘制分面地图的白色边框?

移除geom_sf分面地图的白色边框

问题描述

我改用geom_sf()和coord_sf()绘制分面地图后,始终无法移除地图周围的白色边框。之前使用已弃用的rgdal包搭配coord_cartesian()时没有这个问题,现在换方法后卡壳了。

当前代码

land <- sf::read_sf("./shapefiles/Grey_WA_OR.shp")
land <- sf::st_transform(land, crs = "+proj=longlat +datum=WGS84")

water <- sf::read_sf("./shapefiles/NW_Marine.shp")
water <- sf::st_transform(water, crs = "+proj=longlat +datum=WGS84")

heatmap <- ggplot()+ theme_bw()+
  geom_sf(data = water, fill = "paleturquoise3", color = "turquoise4") +
  geom_sf(data = land, fill='grey96') +
  coord_sf(xlim = c(-126.3, -122.3), ylim = c(48.3, 50.39)) +
  geom_point(data= CPUE.bymonth.mean.nonzero, mapping = aes(x=Lon, y=Lat, 
            size=MeanCPUE), alpha = 0.5, colour= "coral", stroke = 0.7)+  
  geom_point(data = CPUE.bymonth.mean.zeros, mapping = aes(x = Lon, y = Lat, 
                          size = MeanCPUE), alpha = 0.7, color = "gray25") +
  scale_size_continuous(breaks = c(0, 500,1000, 3000), name = "Mean CPUE", 
                        range = c(2.5,15)) +
  theme(axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        axis.title.x = element_blank(), 
        axis.title.y = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())+
  guides(size = guide_legend(override.aes = list(color = 
        c("gray25","coral","coral", "coral"), alpha = 0.6), size = 12))+
  facet_grid(Year ~ Month)+
  theme(
    strip.text.x = element_text(size = 12, color = "black", face = "bold"),
    strip.text.y = element_text(size = 12, color = "black", face = "bold"))

ggsave(filename = "figures/CPUE_map.png", plot = heatmap, 
       width = 12, height = 6, dpi = 600 )

效果对比

当前效果

带白色边框的分面网格地图

期望效果

理想效果

已尝试的方法

  • 使用cowplot包,无效果
  • 设置theme(plot.margin = unit(c(0,0,0,0), "cm"))移除边距,无效

解决方案

要消除白色边框,需针对3个核心点调整:

  1. 关闭坐标扩展:在coord_sf()中添加expand = FALSE,让地图内容完全贴合设定的xlim和ylim,消除边框内的空白。
  2. 移除面板边框:在theme中设置panel.border = element_blank(),这是白色边框的核心来源。
  3. 收紧边距:配合设置plot.margin和分面间距,确保整体无多余空白。

修改后的关键代码片段:

heatmap <- ggplot()+ theme_bw()+
  # 保留原有图层...
  coord_sf(xlim = c(-126.3, -122.3), ylim = c(48.3, 50.39), expand = FALSE) +
  # 保留原有图层...
  theme(
    # 保留原有theme设置...
    panel.border = element_blank(),
    plot.margin = unit(c(0,0,0,0), "cm"),
    panel.spacing = unit(0, "cm") # 新版本ggplot2用这个替代旧的panel.margin
  )

调整后地图会完全贴合分面区域,消除周围白色边框,达到预期效果。


内容的提问来源于stack exchange,提问作者Tim Van Der Stap

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 23:15:54