Jessie Jessie - 20 days ago 8
R Question

R:Plotly - Creating Multiple boxplots in one graph as a group

I have a data set like below for 250 Ids

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


I want to create a boxplot using plotly in R grouping by A,B,C. My boxplot should look like below (Sample plot).

Required Boxplot

But I do not have a variable column to group this.

Is there a way I can create this in R using plot_ly package??
Thanks.

Answer

You can do this with some processing of your data using the tidyr and dplyr packages before you plot. Assume that your data frame is df.

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

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

You would then use plot_data to create your boxplots using plot.ly with your new group and gender variables.

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