for循环在单独的文件中生成并保存多个ggplots [英] for loop to generate and save multiple ggplots in a separate file

查看:67
本文介绍了for循环在单独的文件中生成并保存多个ggplots的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据(TransDat70)总共包含103个变量.第一个102命名为"V1"至"V102",最后一个变量命名为"Time.Min".

My data (TransDat70) contains 103 variables total. The first 102 are named "V1" through "V102", the last variable is names "Time.Min".

我需要针对变量"Time.Min"生成每个变量(V1至V102)的102个ggplots.然后,我需要将所有这些ggplots保存在一个单独的文件(pdf)中,为了相互比较,最好将所有这些ggplots彼此紧挨着放置.

I need to generate 102 ggplots of each variable (V1 through V102) against the variable "Time.Min". I then need to save all these ggplots in a separate file (pdf) preferably all next to/below one another for comparison purposes.

我尝试使用可以在网上找到的代码,但到目前为止,没有一个对我有用.

I tried using code that I was able to find online but none has worked for me so far.

这是我的代码:

var_list = combn(names(TransDat70)[1: 102], 2, simplify = FALSE)
plot_list = list()

for (i in 1: 3) {
    p = ggplot(TransDat70, aes_string(x = var_list[[i]][1], y = var_list[[i]][2])) + geom_point()
    plot_list[[i]] = p
}

for (i in 1: 3) {
    plot70 = paste("iris_plot_", i, ".tiff", sep = "")
    tiff(plot70)
    print(plot_list[[i]])
    dev.off()
}

pdf("plots.pdf")

for (i in 1: 3) {
    print(plot_list[[i]])
}

dev.off()

有什么建议吗?

推荐答案

如果用单独"来表示每个图都在单独的文件中,那该怎么办?

If by separate you meant each plot in a separate file, how about this?

library(ggplot2)

# FAKE DATA AS EXAMPLE
TransDat70 <- data.frame(
  1:10,
  1:10,
  1:10,
  1:10,
  1:10
)

colnames(TransDat70) <- c('V1', 'V2', 'V3', 'V4', 'Time.Min')

for (i in 1:(length(TransDat70) - 1)) {
  p <- ggplot(TransDat70, aes_string(x = paste('V', toString(i), sep=''), y='Time.Min')) + geom_point()
  ggsave(paste('~/Desktop/plot_', i, '.pdf', sep=''), p)
}

有关更多信息,请参见 ggsave 文档选项.

See the ggsave documentation for more options.

如果您打算将它们全部放在一个大文件中,请查看

If you meant to have them all in one big file, take a look at Printing multiple ggplots into a single pdf, multiple plots per page.

但是,对于这么多绘图来说,可能会产生一个很大的文件,这可能会导致打开时出现问题,尤其是在您的绘图中有很多点的情况下.在这种情况下,最好将它们作为单独的文件进行比较.

However, for that many plots it would make a likely make a huge file, which could be problematic to open, especially if you have many points in your plots. In that case it might be better to compare them as separate files.

这篇关于for循环在单独的文件中生成并保存多个ggplots的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆