首页 > 解决方案 > 使用 R tmap 包在 2 行中绘制 3 个地图

问题描述

我正在尝试使用 tmap 包制作的 3 个地图保存一个绘图,其中较大的一个在顶部,另外 2 个在底部,如上面的示例: 在此处输入图像描述

但是使用tmap_arrange()包提供的这种程序,它给了我以下信息:

data(World)
p1 <- tm_shape(World)+tm_polygons()
p2 <- tm_shape(World[World$continent=='South America',])+tm_polygons()
p3 <- tm_shape(World[World$name=='Brazil',])+tm_polygons()

tmap_arrange(p1,p2,p3,nrow=2)

在此处输入图像描述

我尝试使用许多选项,例如将地图导出为图像,然后再次导入到 R 以使用par()and/or组成完整图像split.screen(),但也无法正常工作。有什么办法可以解决这个问题并获得想要的结果?

提前致谢!

标签: rgistmap

解决方案


一种骇人听闻的方法是使用grid包功能。获取每个绘图/地图的输出并将其存储为gTree对象,然后尝试将新对象排列在网格中。

library(tmap)
library(cowplot) # for plot_grid() function - good to arrange multiple plots into a grid
library(grid)
library(gridGraphics)

data(World)

tm_shape(World) + tm_polygons()
g1 <- grid.grab()

tm_shape(World[World$continent == 'South America', ]) + tm_polygons()
g2 <- grid.grab()

tm_shape(World[World$name == 'Brazil', ]) + tm_polygons()
g3 <- grid.grab()

# Try to arrange the plots into a grid using cowplot::plot_grid().
# First bind the p2 and p3 as one plot; 
# adjust distance between them by forcing a NULL plot in between.
p23 <- plot_grid(g2, NULL, g3, rel_widths = c(1, -0.7, 1), nrow = 1)
plot_grid(g1, p23, nrow = 2, scale = c(0.8, 1))

我无法弄清楚如何让它响应这个align论点:/但这也许会让你进入一些探索方向,或者其他人可以编辑/改进这个答案。

# Save the plot
ggsave(filename = "tmap-arrange-grid-1.png", 
       width = 10, height = 6, units = "cm", dpi = 150)

在此处输入图像描述

请注意,最初我认为我可以通过向like添加NULL对象来进行探索,但不幸的是,它不接受它。tmap_arrangetmap_arrange(p1, NULL, p2, p3, nrow = 2)


受这个相关问题启发的另一种方法可能是这样的:

library(grid)

grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow = 2, ncol = 2)))
print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1:2))
print(p2, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(p3, vp = viewport(layout.pos.row = 2, layout.pos.col = 2))

在此处输入图像描述

同样,在这里,我没有时间探索完美地对齐情节,但其他人可能会改进这个答案。


推荐阅读