r - 使用 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()
,但也无法正常工作。有什么办法可以解决这个问题并获得想要的结果?
提前致谢!
解决方案
一种骇人听闻的方法是使用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_arrange
tmap_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))
同样,在这里,我没有时间探索完美地对齐情节,但其他人可能会改进这个答案。
推荐阅读
- r - R中带有createFolds函数的训练和测试集
- vb.net - 如何在图片框的中心张贴标签?
- javascript - querySelectorAll 不显示数组中的所有元素,角度材料
- javascript - 如何使可变返回数而不是功能?
- java - 将 Spring Boot 从 1.5 升级到 2 后,REST 端点给出 404 响应
- python - Python套接字在两台PC之间不起作用
- android - 将 LiveData/ViewModel 与片段一起使用?
- here-api - 为什么我从 Here Routing API 和 Here Maps 网站得到不同的结果?
- svelte - $: 的简化语法将语句标记为反应式
- reactjs - 以编程方式在 react-jsonschema-forms 中设置默认值