Merging or combining few Boxplots into one

Is their a way to merge or combine few boxplots into one

for example i have the below three box plots :

ggplot(mpg,aes(displ))+geom_boxplot()

ggplot(mpg,aes(hwy))+geom_boxplot()

ggplot(mpg,aes(cty))+geom_boxplot()

can i get all of them in one plot ?

thank you

Reshape the data frame into a long format and map an axis to the categorical variable, take a look at this example:

library(ggplot2)
library(tidyr)
library(dplyr)

mpg %>% 
    select(displ, hwy, cty) %>% 
    pivot_longer(cols = everything(), names_to = "Variable", values_to = "Value") %>% 
    ggplot(aes(x = Variable, y = Value, fill = Variable)) +
    geom_boxplot()

Created on 2022-07-29 by the reprex package (v2.0.1)

1 Like

that was amazing ,, thank you for the help

if my data contain more than 70 variables , but i want to do the boxplot only for the numerical variables (around 40 ) .

I tried to apply the same syntax but i found it little bet annoying and time consuming to type all the variable names .

thank you again

You can use a tidyselect helper like where()

your_data_frame %>% 
    select(where(is.numeric)) %>% 
    pivot_longer(cols = everything(), names_to = "Variable", values_to = "Value") %>% 
    ggplot(aes(x = Variable, y = Value, fill = Variable)) +
    geom_boxplot()
2 Likes

great ! that was amazing

can i do a facet_wrap to them also as well ?

thank you so much

Yes, instead of mapping the x axis, use the categorical variable to facet by.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.