2016-11-16 41 views
2

我有一个数据组像下面250 IDSR:Plotly - 在一个图表创建多个箱图作为一个组

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 

我想创建中的R分组使用plotly由A,B,C的箱线图。我的boxplot应该如下图所示(示例图)。

Required Boxplot

但我不具有可变列来此。

有没有一种方法可以在R中使用plot_ly包创建它? 谢谢。

+0

看看'data.table :: melt' – HubertL

+0

@ HubertL谢谢! – Jessie

回答

2

在绘制之前,您可以使用tidyrdplyr程序包对数据进行一些处理。假设你的数据框是df

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

plot_data <- df %>% 
    gather(variable, value, -ID) %>% 
    separate(variable, c("group","gender"), sep = "\\_") 

你会再使用plot_data使用plot.ly与新组和性别变量来创建你的盒形图。

plot_ly(plot_data, x = ~group, y = ~value, color = ~gender, type = "box") %>% 
layout(boxmode = "group") 
+0

谢谢!此方法有效。 – Jessie

2

你可以试试这个简单(这里df是您提供的样本数据,先从):

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 (%)')) 

enter image description here

+0

非常感谢!上述两种方法都适用于这种情况 – Jessie