我正在尝试将ggplot2图添加到列表中,这样我就可以使用ggpubr中的ggarrange函数在多个页面上组织它们。
由于有几百个绘图,我正在使用一个函数来生成和保存绘图,但我无法将绘图返回到环境或将名称写入列表。
我很确定这是一个简单的东西,我错过了,但找不到它。
我使用的绘图功能是:
histFacet.plot <- function(x, results, info, ...) {
md<- names(x) %in% c("rn","Taxa","year","rep","block","column",
"range", "entity_id")
traits <- names(x[ , !md])
for (i in traits) {
i <-ggplot(data = x, aes_string(x = i)) +
geom_histogram(colour="black", fill="white") +
#facet_grid(x$year ~ .) +
theme_bw() +
xlab(paste0(i)) +
ylab("Frequency") +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank()) +
theme(axis.text = element_text(size = 15)) +
theme(axis.title = element_text(size = 15)) +
theme(strip.text = element_text(size = 15))
#ggsave(paste0(i,"_",info,".pdf"),path=paste(results, sep=''))
plotList<- list(plotList, list(i))
print(i)
}
return(i)
}
histFacet.plot(pd,'~/Dropbox/Research_Poland_Lab/AM Panel/Figures/Hist/',
"_raw_2018")
您最大的问题是return(i)
而不是return(plotList)
。在for
循环中使用i
作为迭代器重新分配i
是很奇怪的。特别是当绘图使用i
作为字符串时。。。我会试试这个:
histFacet.plot <- function(x, results, info, ...) {
md <- names(x) %in% c("rn","Taxa","year","rep","block","column",
"range", "entity_id")
traits <- names(x[ , !md])
plotList = list()
for (i in traits) {
thisPlot <- ggplot(data = x, aes_string(x = i)) +
geom_histogram(colour="black", fill="white") +
#facet_grid(x$year ~ .) +
theme_bw() +
xlab(i) +
ylab("Frequency") +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank()) +
theme(axis.text = element_text(size = 15)) +
theme(axis.title = element_text(size = 15)) +
theme(strip.text = element_text(size = 15))
plotList[[i]] = thisPlot
print(i)
}
return(plotList)
}
当然是未测试的,因为您没有共享样本数据。如果您提供了一个小的、可复制的示例数据集,那么很乐意进行测试/调试。
我真的不确定您是希望print(i)
将绘图打印到图形设备上(如果是,请更改为print(thisPlot)
(,还是希望将当前特征打印到控制台上,以通过循环更新进度(如果是的话,请更改至message(i)
,使其易于禁用(。
另外需要注意的是:如果您使用facet,请使用year ~ .
作为公式,而不是x$year ~ .
。如果i
已经是一个chracter,那么paste0(i)
与i
(在您的xlab
中(相同。