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

Time:08-19

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 !

CodePudding user response:

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 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

  • Related