首页 > 解决方案 > 在 for 循环中使用 ggarrange 排列多个图

问题描述

我想使用以下代码在一张图像中排列多个图:

mydataframe <- data.frame(
  number1 = sample(1:140, size=200, replace=TRUE),
  number2 = sample(1:4000, size=200, replace=TRUE),
  number3 = sample(1:30, size=200, replace=TRUE),
  number4 = sample(1:200, size=200, replace=TRUE)
)

unit <- c(
  "number1" = "kmh", 
  "number2" = "rpm", 
  "number3" = "degrees", 
  "number4" = "volts"
)

labels <- c(
  "number1" = "Number 1", 
  "number2" = "Number 2", 
  "number3" = "Number 3", 
  "number4" = "Number 4"
)

for(key in names(unit))
{
  c_plot <- paste0 ("plot_", key) # generate new variable per plot
  
  assign (c_plot, # assign current plot to new variable
          
          ggplot(mydataframe, aes(x=key, y=eval(parse(text = key)))) +
            geom_boxplot() +
            labs (x = labels[key], y = unit[key]) +
            theme(axis.text.x = element_blank())
  )
  
  ggsave(filename = paste0("plots/", key, ".jpg"), plot = eval(parse(text = c_plot))) # save current plot as single image - that works
}

allplots <- ggarrange(plot_number1, plot_number2, plot_number3, plot_number4, # arrange all 4 plots - plot is always the last one generated
                      labels = c("A", "B", "C", "D"),
                      ncol = 2, nrow = 2)

allplots

结果,我得到了一张带有 4 个图的图像(什么是正确的),正确分配了 x 和 y 轴的标签(x 轴的 fe number1 和 y 轴的 mph),但其他一切都是最后一个图的 4 倍 - 相同具有相同箱线图和相同 y 刻度的数据。

奇怪的是,使用 ggsave 保存的图像(保存当前图)执行正确 - 每个图都是使用正确的数据创建的,并且与所有其他图不同。

有谁知道我做错了什么?似乎for循环中的代码的特定部分没有统一到变量“c_plot”并且在循环结束时被覆盖,所以最后最后一个绘图的数据用于所有绘图。

标签: rplot

解决方案


我是正确的。这是一个懒惰的评估问题。

“应用”函数系列,包括 、sapplylapplymapply将函数应用于一系列值。请参阅联机帮助。

下次,请说明您的代码需要哪些包,以便您提供一个独立的、可重现的示例。

library(tidyverse)
library(ggpubr)

plotList <- lapply(
              names(unit),
              function(key) {
                # Need to assign the plot to a variable because 
                # you want to generate the plot AND save to file 
                x <- ggplot(mydataframe, aes(x=key, y=eval(parse(text = key)))) +
                       geom_boxplot() +
                       labs (x = labels[key], y = unit[key]) +
                       theme(axis.text.x = element_blank())
                # No need for the plot argument.  It defaults to the last plot created.
                ggsave(filename = paste0("plots/", key, ".jpg"))
                # Return the plot just created
                x
              }
)

allplots <- ggarrange(plotlist=plotList,
                      labels = c("A", "B", "C", "D"),
                      ncol = 2, nrow = 2)

allplots

给予

在此处输入图像描述


推荐阅读