R:箱线图如何有效地制定数据

R: Boxplot how to formulate data in effective way

我使用的数据是

> head(df2)
       Results Capacity Power  LDI  LDE      LB  PDC   D E1 E2 E3 E4 E5 E6 E7 E8 E9
1 DCNoV2GYesDC       C1  PG11 LDI0 LDE0 LB0.045 PDC0 D10 30 NA 20 3 1 5 NA NA NA 20
2 DCNoV2GYesDC    C0.95  PG11 LDI0 LDE2 LB0.045 PDC0 D10 8  3  NA  8  9 NA NA NA NA
3 DCNoV2GYesDC     C0.9  PG11 LDI0 LDE2 LB0.045 PDC0 D10 8  NA  5  NA  6 7 NA NA NA
4 DCNoV2GYesDC    C0.85  PG11 LDI0 LDE2 LB0.045 PDC0 D10 NA NA NA NA NA NA NA NA NA
5 DCNoV2GYesDC     C0.8  PG11 LDI0 LDE3 LB0.045 PDC0 D10 NA NA NA NA NA NA NA NA NA
6 DCNoV2GYesDC    C0.75  PG11 LDI0 LDE3 LB0.045 PDC0 D10 NA NA  1  1 NA  1 NA 50 70

我写了一个循环在一个脚本中绘制多个 bowplot:

df2 <- myfun2(Impact$X__3, EV)
Box.graph <- function(df2, na.rm = TRUE, ...){
  Caplist <- unique(df2$Capacity) 
y <- df2[df2$Capacity==Caplist[i],1:9]
  for (i in seq_along(Caplist)){
    boxplot <- 
      ggplot(subset(df2, df2$Capacity==Caplist[i]),
             aes(LDI, y=value , colour = LDI), group = df2$Capacity) +
      geom_boxplot() +
      theme(axis.text.x = element_text(size=14))+
      facet_wrap( ~ PDC, ncol =1)+ 
      theme(legend.position = "top")+
      scale_y_continuous("time")+
      scale_x_continuous("LDI")+
      ggtitle(paste(Caplist[i], ' LDE \n', 
                    "time \n",
                    sep=''))
    #save plot as PNG 
    ggsave(plot = last_plot(), file= paste(StoreResults, '/Results/',
                                           Caplist[i], "YesDCNoV2G.png", sep=''), scale=2)
    print(boxplot)
  }
}
#Run the function  
Box.graph(df2)

我遇到的问题是这段代码没有给出错误,运行 也没有。我认为问题在于 y=value 部分不正确或未正确定义。

我试图通过添加一行 y <- df2[df2$Capacity==Caplist[i],1:9] 来解决问题,并且还按照建议在 ggplot 部分添加了 `y= df2[df2$Capacity==Caplist[i],1:9]' here。还是没有结果。有人还指出我应该融化数据:但我不知道对我的数据最有效的方法是什么。

所需的输出是几个箱线图,其值为 E1,E2,E3,E4,E5,E6,E7,E8 and E9。因此,例如第一个箱线图应包含以下值:30 NA 20 3 1 5 NA NA NA 20

请试试这个简化的函数(没有真实数据很难测试):

Box.graph <- function(df2, naRM = TRUE) {
    library(data.table)
    library(ggplot2)

    setDT(df2)
    foo <- melt(df2, c("LDI", "PDC", "Capacity"))[variable %in% paste0("E", 1:9)]
    if (naRM) {
        foo <- foo[!is.na(value)]
    }
    p <- ggplot(foo, aes(LDI, value, fill = LDI)) +
        geom_boxplot() +
        facet_wrap(Capacity ~ PDC)
    ggsave(plot = p, file = paste0(StoreResults, "/Results/YesDCNoV2G.png"), scale=2)
    return(NULL)
}
Box.graph(df2)