如何消除grid.arrange组合ggmap图时的多余内部边距?
解决ggmap地图组合时内部边距异常的问题
我完全懂你这个头疼的问题——用ggmap做的地图在grid.arrange组合时,那些预设的边距总会莫名其妙多出内部间距,而普通散点图就不会,这确实是ggmap和常规ggplot对象在布局处理上的小差异导致的。ggmap生成的图底层会带一些和地图底图绑定的布局属性,导致组合时每个图的边距被完整保留,包括相邻图之间的重复边距,最终间距超出预期。下面给你几个实用的解决办法:
方法1:用Patchwork包替代grid.arrange(最推荐)
Patchwork对ggplot系列对象的布局处理要智能得多,它会自动合并相邻图的重复边距,完美解决你遇到的问题。用法也非常直观:
library(ggmap) library(patchwork) # 生成带自定义边距的地图 map <- get_map(location = "Paris", zoom = 12) ggmap_plot <- ggmap(map) + theme( plot.margin = margin(10, 10, 10, 10, "pt"), plot.background = element_rect(fill = "gray") ) # 组合成3×2网格 (ggmap_plot + ggmap_plot + ggmap_plot) / (ggmap_plot + ggmap_plot + ggmap_plot)
这样组合出来的地图,相邻图之间的内部边距会自动合并,和你组合散点图时的效果一致。
方法2:手动调整每个地图的边距(适配grid.arrange)
如果你坚持要用grid.arrange,可以针对不同位置的地图设置差异化的边距,避免相邻边距重复叠加:
library(ggmap) library(gridExtra) map <- get_map(location = "Paris", zoom = 12) # 为不同位置的图设置不同边距:左右相邻的图共享部分边距 plot_left <- ggmap(map) + theme( plot.margin = margin(10, 5, 10, 10, "pt"), plot.background = element_rect(fill = "gray") ) plot_right <- ggmap(map) + theme( plot.margin = margin(10, 10, 10, 5, "pt"), plot.background = element_rect(fill = "gray") ) # 组合3×2网格 grid.arrange( plot_left, plot_right, plot_left, plot_right, plot_left, plot_right, ncol = 2, nrow = 3 )
这里把左侧图的右边距和右侧图的左边距减半,组合后整体间距就和你预设的一致了。
方法3:用gtable修改地图布局结构
如果上面的方法都不满足需求,还可以直接操作gtable对象,手动移除地图中多余的内部边距:
library(ggmap) library(gridExtra) library(gtable) map <- get_map(location = "Paris", zoom = 12) ggmap_plot <- ggmap(map) + theme( plot.margin = margin(10, 10, 10, 10, "pt"), plot.background = element_rect(fill = "gray") ) # 将ggplot对象转为gtable g <- ggplotGrob(ggmap_plot) # 移除gtable中不必要的边缘行/列(可通过gtable_show_layout(g)查看结构) g$widths[1] <- unit(0, "pt") # 移除左侧多余边距 g$widths[ncol(g)] <- unit(0, "pt") # 移除右侧多余边距 g$heights[1] <- unit(0, "pt") # 移除顶部多余边距 g$heights[nrow(g)] <- unit(0, "pt") # 移除底部多余边距 # 组合处理后的gtable对象 grid.arrange(g, g, g, g, g, g, ncol=2, nrow=3)
为什么散点图没问题?
常规ggplot散点图的plot.margin是直接作用于绘图区域的独立设置,grid.arrange在组合时会默认处理相邻边距的叠加;但ggmap生成的图因为绑定了地图底图的坐标系统(coord_fixed),底层布局会保留完整的边距设置,导致组合时每个图的边距都被单独计算,最终出现额外的内部间距。
内容的提问来源于stack exchange,提问作者Daniel Baldassarre
相关产品推荐
相关产品推荐

