Jessie Jessie - 1 year ago 145
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??

Answer Source

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.


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

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

plot_ly(plot_data, x = ~group, y = ~value, color = ~gender, type = "box") %>%
layout(boxmode = "group")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download