1
votes

I have a dataset in R that includes 6 quantitative variables and another variable that is binary. My objective is, for each cuantitative variable, to create a boxplot that compares the values of this variable for the two levels of the binary variable, and I want the 6 images to be put into a single figure in R using ggplot.

Consider the following example to show what I am saying. So far, I know how to solve this using the default "boxplot" function in R:

X = data.frame(a = c(rep("T", 5), rep("F", 5)), 
               b = rnorm(10), 
               c = runif(10))

par(mfrow = c(1, 2))
boxplot(b ~ a, data = X)
boxplot(c ~ a, data = X)

And I know how to create the two boxplots I want using ggplot:

library(ggplot2)

ggplot(X, aes(x = a, y = b)) + 
  geom_boxplot(aes(fill = a))
ggplot(X, aes(x = a, y = c)) + 
  geom_boxplot(aes(fill = a))

What I do not know is how to get the two ggplot boxplots displayed into a single figure.

1

1 Answers

2
votes

Is this what you need? I think it's better to fill with "id" than a. EDIT: FINAL ANSWER

X %>% 
  gather("id","value",2:3) %>% 
  group_by(id) %>% 
  ggplot(aes(a,value,fill=id))+geom_boxplot()+facet_wrap(~id)

Original:

ANSWER: If you want to fill with a, then:

X %>% 
  gather("id","value",2:3) %>% 
  group_by(id) %>% 
  ggplot(aes(id,value))+geom_boxplot(aes(fill=a))

Otherwise:

 library(tidyverse)
    X %>% 
      gather("id","value",2:3) %>% 
      group_by(id) %>% 
      ggplot(aes(a,value,fill=id))+geom_boxplot()