r - 页面上的多个绘图

标签 r ggplot2 visualization

我希望它在单个页面上有 4 个图,而不是每页只有 1 个图,有没有办法可以使用循环中的 ggarrange 在单个页面上有 4 个不同的图?

library(ggplot2)

n <- 10 # number of plots
x <- rnorm(50, mean = 20)
y <- 2*x + 1 + rnorm(50)
df <- data.frame(x = x, y = y)
  
pdf("test.pdf", onefile = TRUE)
for(i in seq(n)){
  df$x <- df$x + rnorm(50, sd = 0.01)
  df$y <- df$y + rnorm(50, sd = 0.01)
  p <- ggplot(data = df) + aes(x, y) + 
    geom_point()
  print(p)
}
dev.off() # close device

最佳答案

你可以试试这个 -

# number of plots
n <- 10 
#Create a dataframe
x <- rnorm(50, mean = 20)
y <- 2*x + 1 + rnorm(50)
df <- data.frame(x = x, y = y)

pdf("test.pdf", onefile = TRUE)
#for n = 10, loop will run 3 times. 
#It will generate 4, 4, and 2 plots
for(i in seq(ceiling(n/4))) {
  #For the last page
  if(n > 4) k <- 4 else k <- n
  n <- n - 4
  #Create a list to store the plots
  plot_list <- vector('list', k)
  for(j in 1:k) {
    df$x <- df$x + rnorm(50, sd = 0.01)
    df$y <- df$y + rnorm(50, sd = 0.01)
    plot_list[[j]] <- ggplot(data = df) + aes(x, y) + geom_point() 
  }
  #Print multiple plots together
  print(do.call(gridExtra::grid.arrange, plot_list))
}
dev.off()

关于r - 页面上的多个绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68419243/

相关文章:

修改 x 轴上的刻度数?

r - 像在 gtable 中一样制作 ggplot 面板背景

r - 如何消除 "NA/NaN/Inf in foreign function call (arg 7)"使用 randomForest 运行预测

r - 将 ggplotly 和 ggplot 与拼凑而成?

r - 在R中绘制简单的中介图

r - 当我的 ggplot2 语法合理时,如何处理 R CMD 检查 "no visible binding for global variable"注释?

r - 想知道如何输出我在经济学家杂志上看到的图表

python - keras模型中卷积层的可视化

javascript - d3 时间轴的限制缩放级别

java - Java 的免费时间线可视化 API?