Superpose two boxplots with a different number of data in only one graph

Viewed 41

In r, is there a solution to superpose two boxplots in only one graph with a different number of data? (With a different color for data1 and data2)

Rather than doing this :

data1 <- data.frame(T1_A=rnorm(37),T2_A=rnorm(37),T3_A=rnorm(37))
data2 <- data.frame(T1_B=rnorm(25),T2_B=rnorm(25),T3_B=rnorm(25))
par(mfrow = c(2,1)
boxplot(data1)
boxplot(data2)

Thanks !

2 Answers

In ggplot, you can achieve the same effect like this:

library(tidyverse)

bind_rows(pivot_longer(data1, everything()),
          pivot_longer(data2, everything()),
          .id = 'dataset') %>%
  ggplot(aes(name, value, fill = dataset)) +
  geom_boxplot() +
  facet_wrap(~dataset, nrow = 2, scales = 'free_x', drop = TRUE)

enter image description here

Or if you want them all in the same panel,

bind_rows(pivot_longer(data1, everything()),
          pivot_longer(data2, everything()),
          .id = 'dataset') %>%
  ggplot(aes(name, value, fill = dataset)) +
  geom_boxplot() 

enter image description here

Base option:

You could create use boxplot calls where the second has add=true to combine them in one graph. With at you can define the colnames on the x-axis like this:

data1 <- data.frame(T1_A=rnorm(37),T2_A=rnorm(37),T3_A=rnorm(37))
data2 <- data.frame(T1_B=rnorm(25),T2_B=rnorm(25),T3_B=rnorm(25))
boxplot(data1, at = 0:2*3+1, border = "red", xlim = c(0,9))
boxplot(data2, at = 0:2*3+2, border = "blue", add = TRUE)

Created on 2022-08-18 with reprex v2.0.2

Related