Home > Software design >  how to create multiple boxplots from the same dataframe?
how to create multiple boxplots from the same dataframe?

Time:02-12

I have a data frame like this:

df <- data.frame(var_1 = c(1,2,3,4,5,6,7,8,9), 
                 var_2 = c(21,23,34,45,23,56,76,54,65),
                 var_3 = c(6,5,4,3,5,7,3,2,5),
                 label = c(1,1,1,2,1,2,2,1,2))

I want to create side by side (or tile) box plots such that the first box plot is

boxplot(var_1~label, df)

the second box plot is

boxplot(var_2~label, df)

and so on. Is there a way to do this without me having to type box plot command each time? For example, some command that iteratively matches all the columns against label and draw a box plot for each?

CodePudding user response:

Try:

library(tidyverse)

df %>%
  pivot_longer(-label) %>%
  ggplot(aes(label, value))  
  geom_boxplot()  
  facet_wrap(vars(name))
  • Related