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).
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With