r语言 - 从具有统计信息的列表生成绘图



这可能对一段代码要求太多了,但这里是:

我可以:

  1. 在大数据框架列表上制作多个单独的ggplot ?
  2. 在数据框列表中的每个数据框中以编程方式跨一小组数据进行方差分析?

我有一个很长的数据集像是存储在object "a":

Volunteer Conditions  Time Compounds Conc
V1       Cond1     0    HBA      0.2
V1       Cond1     0    HBA      0.19
V1       Cond1     0    HBA      0.21
V1       Cond2     0    HBA      0.42
..         ..      ..   ..        ..
V1       Cond1      4    HBA      0.45
V1       Cond1      4    HBA      0.45
V1       Cond1      4    HBA      0.45
V1       Cond2      4    HBA      0.48
..       .     ..       ..

在志愿者(V1, V2,V3..),条件(条件1,条件2,条件3..),时间(0,4,8)和化合物(HBA, BPA, HPP, BPV..)上重复了大约939个观察值。

已被分割成:

b<-split(a, f=a$Compounds)

我想试着画个盒子图。

当对单个化合物执行时,它有效,但我可以将其应用于b吗?

例如:
ggplot(data = b$HBA, 
aes(x=as.factor(Time), y=(Conc)))+
geom_boxplot(width=0.5)+
facet_wrap(Volunteer~Conditions, ncol = 3)+
theme_bw()

行之有效。

但不适合b[[i]]或ggplot中的类似内容。是否也可以自动生成一个ggplot并将其保存为plot_HBA.jpg等循环名称,然后保存为plot_BPA.jpg(这是列表中下一个化合物的名称)。

我还想对一个化合物内、一个志愿者内、一个条件内的时间点(0、4、8)的重复观察进行方差分析。

我试着:

library(rstatix)
library(tidyverse)
a%>%group_by(Compounds,Condition,Volunteer)%>%anova_test(Conc~Time)

但是它不能说平方和的残差是0

我希望在每个方面的箱形图上有p值的括号,以表示整个时间序列中具有统计意义的变化。

您可以在for循环中完成此操作,但我认为定义一个函数来创建图(按组合名称过滤数据集),然后使用purrr::map对每个组合名称运行该函数会更简洁一些。您可以向函数添加参数,例如,使保存绘图成为一个选项,以防您不总是希望它保存文件。

library(dplyr)
library(purrr)
library(ggplot2)
#Create a sample data set similar to the example
set.seed(1)
Volunteer <- rep(c("V1","V2","V3","V4"), each = 4, 10)
Conditions <- rep(c("Condition1","Condition2","Condition3","Condition4"), each = 2, 20)
Time <- c(rep(c(0,4,8), 53),0)
Compounds <- rep(c("HBA", "BPA","HPP","BPV"), 40)
Conc <-  runif(160, 0,1)
a <- tibble(Volunteer, Conditions, Time, Compounds, Conc)
#Define a function that creates (and saves) a 
#boxplot for each compound
boxplot_by_compound <- function(df, compound) {
df %>% filter(Compounds == compound) %>% 
ggplot(aes(x=as.factor(Time), y=Conc))+
geom_boxplot(width=0.5)+
facet_wrap(Volunteer~Conditions, ncol = 3)+
theme_bw()
ggsave(paste0("plot_",compound,".jpg"))
last_plot() #If you want to see it in addition to just saving to file
}
#Instead of splitting the dataset into a list, 
#just get a vector of compound names
compound_names<-unique(a$Compounds)
#Map the list of compound names to the boxplot function
map(compound_names, ~ boxplot_by_compound(a, .x))

最新更新