R:Plotly-在一个图形中作为一个组创建多个箱线图

R:Plotly-在一个图形中作为一个组创建多个箱线图,r,plotly,R,Plotly,我有一个250个ID的数据集,如下所示 ID A_Male A_Female B_Male B_Female C_Male C_Female 1 25 75 40 60 20 80 2 30 70 50 50 80 20 3 50 50 30 70 20 80 我想通过a、B、C在R分组中使用plotly创建一个箱线图。我的箱线图应该如下所

我有一个250个ID的数据集,如下所示

ID A_Male A_Female B_Male B_Female C_Male C_Female
1    25     75      40     60        20    80
2    30     70      50     50        80    20
3    50     50      30     70        20    80
我想通过a、B、C在R分组中使用plotly创建一个箱线图。我的箱线图应该如下所示(示例图)

但我没有一个变量列来对其进行分组

有没有一种方法可以用plot_-ly软件包在R中创建此功能??
谢谢。

在绘图之前,您可以使用
tidyr
dplyr
软件包对数据进行一些处理。假设您的数据帧是
df

library(dplyr)
library(tidyr)
library(plotly)

plot_data <- df %>%
  gather(variable, value, -ID) %>%
  separate(variable, c("group","gender"), sep = "\\_")
您可以简单地尝试一下(首先,df是您提供的示例数据):


df查看
data.table::melt
非常感谢!上述两种方法都适用于此场景
plot_ly(plot_data, x = ~group, y = ~value, color = ~gender, type = "box") 
df <- melt(df, id='ID')
df[c('type', 'gender')] <- do.call(rbind, strsplit(as.character(df$variable), split='_'))

plot_ly(df, x = type, y = value, color = gender, type = "box") %>% 
         layout(boxmode = "group", 
         xaxis = list(title=''), 
         yaxis = list(title='Percentage (%)'))