如何移除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个核心点调整:
- 关闭坐标扩展:在
coord_sf()中添加expand = FALSE,让地图内容完全贴合设定的xlim和ylim,消除边框内的空白。 - 移除面板边框:在
theme中设置panel.border = element_blank(),这是白色边框的核心来源。 - 收紧边距:配合设置
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
相关产品推荐
相关产品推荐

