【问题标题】:Saving multiple GGplots to a pdf, multiple on one page in a for loop将多个GGplots保存为pdf,在for循环中的一页上保存多个
【发布时间】:2021-09-05 22:59:08
【问题描述】:

我正在尝试保存多个 ggplots,这些 ggplots 本质上是对每列进行直方图。理想情况下,我希望每页有 2 或 3 个图表,但现在我可以每页只有 1 个。 ggplots 看起来不错,但我似乎无法正确保存 ggplots(尽管可能没有正确保存)。

item_set <- unique(df$Item_number)
for(i in 1:length(item_set)){
  n <- as.character(item_set[i])
  temp <- wide_data[, grep(n, names(wide_data))]
  temp <- temp[, grep("Time", names(temp))]
  coln <- colnames(temp)
  
  ggplot(data = temp, aes_string(x = coln)) + geom_histogram(color = "black", fill = "white", bins = 70)
  ggsave("Time Spent - Entire Sample.pdf")
   
}

因此,对于每个 ggplot,它基本上只是逐列、按列名(coln)并创建一个直方图。如何将所有这些保存到一个 pdf 中?

【问题讨论】:

标签: r ggplot2


【解决方案1】:

也许您会发现这个在循环中创建 ggplots 的示例很有用。

# Plot separate ggplot figures in a loop.
library(ggplot2)

# Make list of variable names to loop over.
var_list = combn(names(iris)[1:3], 2, simplify=FALSE)

# Make plots.
plot_list = list()
for (i in 1:3) {
    p = ggplot(iris, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) +
        geom_point(size=3, aes(colour=Species))
    plot_list[[i]] = p
}

# Save plots to tiff. Makes a separate file for each plot.
for (i in 1:3) {
    file_name = paste("iris_plot_", i, ".tiff", sep="")
    tiff(file_name)
    print(plot_list[[i]])
    dev.off()
}

# Another option: create pdf where each page is a separate plot.
pdf("plots.pdf")
for (i in 1:3) {
    print(plot_list[[i]])
}
dev.off()

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 2017-05-06
    • 2020-09-07
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多