如何在R中进行数据操作之前和之后使用ggplot为ggarrange绘制“持久”图

问题描述 投票:1回答:1

我正在尝试通过for循环为数据集中的多列创建数据操作前后的数据比较图。最终,我想将所有比较图保存到一个pdf文件中。首先,我先生成图,然后处理数据,再生成图,然后希望通过ggarrange使其并排(我也尝试了gridExtra的grid.arrange,但这不能解决问题)。但是,我得到的是数据操作后的相同图(尽管标题不同)。

这里是可复制的示例:

library(rlist)
library(ggplot2)
library(ggpubr)
head(iris)
plot_before <-  list()
plot_after <- list()
plots <- list()

for (i in 1:4){
  p <-  ggplot(iris,aes(iris[,i])) + geom_histogram()+ggtitle(paste0(i,"_pre"))
  print(p)
  plot_before <- list.append(plot_before,p)
  #do something with your data
  iris[,i] <- 3*iris[,i]
  p2 <-  ggplot(iris,aes(iris[,i])) + geom_histogram()+ggtitle(paste0(i,"_post"))
  print(p2)
  plot_after <- list.append(plot_after, p2)
  q <-  ggarrange(p,p2)  #here, p is already linked to modified data
  print(q)
  plots <- list.append(plots, q)
}
#try to access plots from lists
for (i in 1:4){
  print(plot_before[[i]])
  print(plot_after[[i]])
  print(plots[[i]])
}

我想这与ggplot创建“仅”链接到数据的图形对象有关,因此,当我再次打印它时,它再次访问数据并获取经过操纵的数据,而不是获取先前的“快照”。将图形保存到单独的列表中也无济于事,它们也“链接”到操纵数据。有没有办法制作一个持久的ggplot对象,而不是将其链接到数据?

r object ggplot2 persistent
1个回答
0
投票

拼凑而成的套件有帮助。一个选项是创建一个绘图列表列表,然后展平该列表,并使用patchwork::wrap_plots

library(tidyverse)
library(patchwork)
ls_plots <- map(1:4, function(i){
  p <-  ggplot(iris,aes(iris[,i])) + 
    geom_histogram()+ 
    ggtitle(paste0(i,"_pre"))
  #do something with your data
  iris[,i] <- 3*iris[,i]
  p2 <-  ggplot(iris,aes(iris[,i])) + 
    geom_histogram()+
    ggtitle(paste0(i,"_post"))
p_list <- list(p,p2)
}
)

ls_unnest <- do.call(list, unlist(ls_plots, recursive=FALSE))
wrap_plots(ls_unnest, ncol = 2)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

“”

reprex package(v0.3.0)在2020-05-07创建

有用的线程:How to flatten a list of lists?

© www.soinside.com 2019 - 2024. All rights reserved.