[英]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)
}
將函數應用於兩個數據幀后,我會將兩者都綁定以獲得最終的數據幀“數據”。
所需的情節最終將是:
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())
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.