Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

r - ggarrange generates an empty pdf file

I am dealing with a function that takes a big data frame (36 rows and 194 columns) which performs a Principal Component Analysis and then generates a list of plots where I have the combination of 26 Principal Components which are 325 in total, using 'expand.grid'.

My problem is that when I am using ggarrange(), from ggpubr, to merge all the plots in only one pdf file, this file is empty.

My code:

a = 26
row.pairs = 325

PC.Graph <- function(df, col1, col2, tag, id){
  df1 <- df[,-c(col1:col2)]
  pca <- prcomp(df1, scale. = T)
  pc.summ <- summary(pca)
  a <- sum(pc.summ$importance[3,] < 0.975)
  b <- c(1:a)
  pc.grid <- expand.grid(b, b)
  pc.pairs <- pc.grid[pc.grid$Var1 < pc.grid$Var2,]
  row.pairs <- nrow(pc.pairs)
  components <- c(1:row.pairs)
  S.apply.FUN <- function(x){
    c <- sapply(pc.pairs, "[", x, simplify = F)
    pcx <- c$Var1
    pcy <- c$Var2
    df2 <- df
    row.names(df2) <- df[, tag]
    name = paste("PCA_", pcx, "_vs_", pcy)
    autoplot(pca, data = df2, colour = id, label = T, label.repel = T, main = name,
             x = pcx, y = pcy)
  }
  all.plots <- Map(S.apply.FUN, components)
  pdf(file = "All_PC.pdf", width = 50, height = 70)
  print(ggarrange(all.plots))
  dev.off()
}

PC.Graph(Final_DF, col1 = 1, col2 = 5, tag = "Sample", id = "Maturation")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would have to pass a plotlist to ggarrange, but I am not sure you would get any useful plot out of that plot area in the PDF file, so I would advise you to split the plotlist into chunks (e.g. of 20) and plot these to multiple pages.

Specifically, I would export all.plots from your PC.Graph function (and remove the code to write to PDF there).

I would also change the expand.grid(b, b) to t(combn(b, 2)), since you don't need to plot the PC combinations twice.

Then I would do something like this:

# export the full list of plots
plots <- PC.Graph(Final_DF, col1 = 1, col2 = 5, tag = "Sample", id = "Maturation")

# split the plotlist
splitPlots <- split(plots, ceiling(seq_along(plots)/20))
plotPlots <- function(x){
    out <- cowplot::plot_grid(plotlist = x, ncol = 5, nrow = 4)
    plot(out)
}
pdf(file = "All_PC.pdf", width = 50, height = 45)
lapply(splitPlots, plotPlots)
dev.off()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...