如何转换我的数据以在 R 中创建分组箱线图?

How can I transform my data to create a grouped boxplot in R?

我在尝试使用 R 中的 ggplot 创建分组箱线图时遇到了一些困难。我有一个数据框需要转换才能获得所需的数据结构。

我的数据如下:

我有两个数据框:

# data frame 1: Method 1

F1 <- c(10,2,3,5,6)
F2 <- c(33, 45, 6, 8, 9)
F3 <- c(44, 55, 10, 23, 44)
Method <- rep("Method1", 5)
data1 = data.frame( F1, F2, F3, Method)

# data frame 2: Method 2

F1 <- c(11,5,3,8,6)
F2 <- c(31, 35, 6, 8, 11)
F3 <- c(44, 55, 12, 23, 41)
Method <- rep("Method2", 5)

data2 = data.frame( F1, F2, F3, Method)

我想创建一个分组箱线图来比较两种方法的 F1、F2 和 F3,为此我已经转换了我的数据框以便在函数 ggplot 中输入正确的值。我认为正确的结构如下:

为此我编写了以下函数:

transform_data <- function(df){
  
dlist = list()
  
  for( f in names(df)){
    # The for loop means to create a df for each feature with the desired structure
    
    Values = df$f
    Method = df$method
    data = data.frame(column_value ,  pipeline)
    data$feature = f
    data append to dlist # Can't find the way to do this

  }
  final_df = do.call(rbind, dlist) # The created data frames are finally bound
  return(final_df)
}

将函数应用到两个数据帧后,我将对两者进行 rbind 以获得最终数据帧 'data'。

最终想要的情节是:

ggplot(data, aes(x=Feature, y=Values, fill=Method)) + 
  geom_boxplot()

我的数据框显然要复杂得多。 :(

欢迎任何评论。 非常感谢,

雷切尔

也许您正在寻找这个。您可以使用 bind_rows()pivot_longer() 保留方法变量。之后,您可以为每种方法使用构面设计绘图。这里的代码:

library(dplyr)
library(tidyr)
library(ggplot2)
#Code
data1 %>% bind_rows(data2) %>%
  pivot_longer(-Method) %>%
  ggplot(aes(x=name,y=value,fill=name))+
  geom_boxplot()+
  facet_wrap(.~Method,nrow = 1,strip.position = 'bottom')+
  theme_bw()+
  theme(strip.placement = 'outside',
        strip.background = element_blank())

输出: