首页 > 解决方案 > 我无法将我的地块放到一个网格中,请帮助纠正我的代码

问题描述

我有 11 个图并使用循环函数来绘制它们,请参见下面的代码。但是,我不能让它们只放在 1 页或更少的页面中。地块实际上太大了。我正在使用 R 软件并在 RMarkdown 中编写我的工作。我花了将近整整一周的时间试图解决这个问题。

  group_by(Firm_category) %>%
  doo(
    ~ggboxplot(
      data =., x = "Means.type", y = "means",
      fill ="grey", palette = "npg", legend = "none",
      ggtheme = theme_pubr()
      ), 
    result = "plots"
  )
graph3

# Add statistical tests to each corresponding plot

Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
  graph3.i <- graph3$plots[[i]] + 
    labs(title = Firm_category[i]) +
    stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
  print(graph3.i)
}

#output3.long data sample below as comments
#Firm_category  billmonth  Means.type  means
#Agric          1           Before       38.4444
#Agric          1           After        51.9

完整的数据在我的 github 上:https ://github.com/Fridahnyakundi/Descriptives-in-R/blob/master/Output3.csv 此代码打印所有图表,但在 4 页中。我想将它们分组到一个网格中。我试图在我最后一个大括号之前添加所有这些代码,但没有一个有效,请帮帮我。

library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))

library(ggpubr)
print(ggarrange(graph3.i[1:11], nrow = 4, ncol = 3))

我也尝试了 gridExtra 命令(它们似乎都在做同样的事情)。我是一个有错误的人,我想这与我的清单有关。我在这里读了很多类似的工作,有些建议

dev.new() 
dev.off()

我还是不明白他们做了什么。但是添加它们中的任何一个都会导致我的代码停止。我尝试定义我的“for”循环函数说调用它“XX”,然后调用它来制作一个图表列表,但它返回 NULL 输出。

我尝试定义一个空列表(正如我在此处阅读的一些答案),然后计算它们以制作一个可以打印的列表,但我遇到了很多错误。我已经这样做了将近 3 天,并将感谢您在解决此问题方面的帮助。谢谢!

标签: rfor-loopggplot2ggpubrcowplot

解决方案


我试图完成你的代码......这有效(但我没有你的'stat.test'对象)。基本上,我在循环中添加了一个graph3.i <- list()并替换graph3.i了..这是你想做的吗?


library(magrittr)
library(dplyr)
library(rstatix)
library(ggplot2)
library(ggpubr)
data <- read.csv(url('http://raw.githubusercontent.com/Fridahnyakundi/Descriptives-in-R/master/Output3.csv'))
graph3 <- data %>% group_by(Firm_category) %>%
  doo(
    ~ggboxplot(
      data =., x = "Means.type", y = "means",
      fill ="grey", palette = "npg", legend = "none",
      ggtheme = theme_pubr()
    ), 
    result = "plots"
  )
graph3

# Add statistical tests to each corresponding plot
graph3.i <- list()
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
  graph3.i[[i]] <- graph3$plots[[i]] + 
    labs(title = Firm_category[i]) # +
    # stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
  print(graph3.i)
}


library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))

推荐阅读