【问题标题】:Combine plots of different classes in R在R中组合不同类别的图
【发布时间】:2021-03-31 02:16:13
【问题描述】:

我正在处理 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, 0.5, -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,  coord_equal = F, geom_raster = 1) + theme(legend.position = "none", axis.title = element_blank(), 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 中自动化该过程。我也愿意接受建议,如何用其他编程语言来做,只是它可以自动化这个过程。 就我而言,切换到不同的课程不是一种选择。

【问题讨论】:

    标签: r ggplot2 plot tmap


    【解决方案1】:

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

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

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

    现在你可以做

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-16
      • 1970-01-01
      • 2021-07-15
      • 2023-04-07
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多