1

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.

Adela
  • 1,757
  • 19
  • 37
  • Related [Plotting two variables as lines using ggplot2 on the same graph](https://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-on-the-same-graph) – markus Jan 22 '19 at 11:43

1 Answers1

2

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()
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • Thanks for your answer, but it is not what I am looking for. Your code generates a figure that compares the "F" values of a and b, and the "T" values of a and b. What I am looking is a figure that includes two plots. The first one, a comparison of "T" vs "F" values for "a", and the second one a comparison for "T"vs"F" values of "b". Something similar to the figure that one can obtain using par(mfrow=c(1,2)) and then creating two normal boxplots – Álvaro Méndez Civieta Jan 22 '19 at 12:13
  • @ÁlvaroMéndezCivieta check my edit! It compares F vs T for b and F vs T for c – NelsonGon Jan 22 '19 at 12:30