Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

plotly

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.

like image 713
Jessie Avatar asked Nov 16 '16 02:11

Jessie


People also ask

How do you put multiple Boxplots on one graph in R?

In this article, we will learn how to plot multiple boxplot in one graph in R Programming Language. This can be accomplished by using boxplot() function, and we can also pass in a list, data frame or multiple vectors to it. For this purpose, we need to put name of data into boxplot() function as input.

How do I group Boxplots in R?

In order to create a box plot by group in R you can pass a formula of the form y ~ x , being x a numerical variable and y a categoriacal variable to the boxplot function. You can pass the variables accessing the data from the data frame using the dollar sign or subsetting the data frame.


1 Answers

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") 
like image 141
Jake Kaupp Avatar answered Sep 22 '22 05:09

Jake Kaupp