首页 > 解决方案 > R在for循环内生成图不流动标准尺寸?

问题描述

我编写了一个 for 循环来制作图表矩阵,但是我编写的代码如下

par(mfrow = c(4, 4))

for (i in c(6:17)) {
  print(ggpubr::ggboxplot(logdat, 
                          x = "Diagnostic", 
                          y = names(logdat)[i] , 
                          color = "Diagnostic", 
                          add = "jitter") + 
    stat_compare_means(comparisons = my_comparisons,
                       method = "t.test")) 
}

只显示单个图表,而不是我想要的矩阵

标签: rggplot2plot

解决方案


您正在使用ggboxplotfrom ggpubrwhich is based on ggplot2,它基于grid图形系统。不幸的是,grid图形不适用于baseR 图形,因此设置par也不起作用。要安排由库构建在其之上创建的图,grid请使用grid.arrangefromgridExtra包。请参见下面的示例:

library(ggpubr)
data("ToothGrowth")
df <- ToothGrowth
grobsList <- list()
for (i in c(1:4)) {

  p <- ggboxplot(df, x = "dose", y = "len", width = 0.8)
  grobsList <- c(grobsList, list(p))
}


gridExtra::grid.arrange(
  grobs = grobsList, ncol = 2, nrow = 2)

您也可以尝试使用marrangeGrob,但它可能会在当前图形窗口之外创建绘图。

当创建所需数量的图时,您还可以在循环内渲染图:

library(ggpubr)
data("ToothGrowth")
df <- ToothGrowth
grobsList <- list()

for (i in c(1:7)) {

  p <- ggboxplot(df, x = "dose", y = "len", width = 0.8)
  grobsList <- c(grobsList, list(p))

  if(length(grobsList) == 4) {
    # print the result
    gridExtra::grid.arrange(
      grobs = grobsList, ncol = 2, nrow = 2)
    grobsList <- list() # reset the list containing the plots
  }
}

# print the remaining plots
if(length(grobsList) > 0) {
  gridExtra::grid.arrange(
    grobs = grobsList, ncol = 2, nrow = 2)
}

推荐阅读