微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 R 中组合不同类的图

如何解决在 R 中组合不同类的图

我正在处理 r 中不同类别的图,即 tmap(主要图)和 ggplot(代表次要信息)。

library(raster)
library(tmap)
library(RStoolBox)
library(gridExtra)
library(ggplot2)

data("World")
r1 <- raster(ncol=2,nrow=2)
values(r1) <- c(1.5,-0.5,0.5,-1.5)

r2 <- raster(ncol=2,nrow=2)
values(r2) <- c(1,1,-1.5)

# Then I create two tmap objects and two ggplot objects
tm1 <- tm_shape(World) + tm_polygons()  
tm2 <- tm_shape(World) + tm_polygons()

gg1 <- ggR(r1,coord_equal = F,geom_raster = 1) + theme(legend.position = "none",axis.title = element_blank(),axis.text = element_text(size = 3.5))
gg2 <- ggR(r2,axis.text = element_text(size = 3.5))

# Save each separately
# 1 tmap
current.mode <- tmap_mode("plot")
tmap_plot <- tmap_arrange(tm1,tm2,ncol = 1,nrow = 2)
tmap_save(tmap_plot,"tmap_plot.png",height = 8,width = 6)

# 2 ggplot
g <- arrangeGrob(gg1,gg2)
ggsave(file = "ggplot.png",g,height = 1.75,width = 1.75)

目前,我单独保存每个类,并使用手动编辑工具将它们组合起来。我正在寻找一个解决方案,如何在 r 中自动化该过程。我也愿意接受建议,如何用其他编程语言来做,只是它可以自动化这个过程。 就我而言,切换到不同的课程不是一种选择。

enter image description here

解决方法

您可以使用 grid::viewport 直接在 tmap 上绘制 ggplots。

首先,加载 grid 并设置所需的视口位置和尺寸:

library(grid)

subplot_vp <- viewport(x = 0.15,y = 0.35,width = unit(0.25,"npc"),height = unit(0.25,name = "inset")

现在可以了

tm1
grid.draw(grobTree(ggplotGrob(gg1),vp = subplot_vp))

enter image description here

tm2
grid.draw(grobTree(ggplotGrob(gg2),vp = subplot_vp))

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。