r - 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"))
}
只显示单个图表,而不是我想要的矩阵
解决方案
您正在使用ggboxplot
from ggpubr
which is based on ggplot2
,它基于grid
图形系统。不幸的是,grid
图形不适用于base
R 图形,因此设置par
也不起作用。要安排由库构建在其之上创建的图,grid
请使用grid.arrange
fromgridExtra
包。请参见下面的示例:
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)
}
推荐阅读
- php - 如何从选项中获取输入,而我必须将数据输入到同一数据库的两个表中,基于选项数据将被插入
- php - 注意:未定义的偏移量:嵌套数组上的 0
- java - 如何在二维数组上使用比较器对用户输入进行排序
- roku - Roku 中的 roRegistrySection 问题?
- java - Kotlin 的主要构造函数的参数是完全私有的还是仅适用于 Java 代码?
- java - 在wiremock中使用ResponseTransformer总是得到空响应
- google-bigquery - 没有足够的资源用于查询计划
- python - 以通用方式比较 Excel 列并用一些颜色突出显示差异
- java - openhtmltopdf是否支持外部css
- java - 如何仅绘制传感器的当前数据点?