Home > OS >  R multiple boxplots
R multiple boxplots

Time:08-19

I have a question regarding multiple boxplots. Assume we have a data structure like this:

a <- rnorm(100, 0, 1)
b <- rnorm(100, 0, 1)
c <- rbinom(100, 1, 0.5)

My task is to create a boxplot of a and b for each group of c. However, it needs to be in the same plot. Ideally: Boxplot for a and b side by side for group 0 and next to it boxplot for a and b for group 1 and all together in one graphic.

I tried several thinks, but only the seperate plots are working:

boxplot(a ~ as.factor(c)) 

and

boxplot(b ~ as.factor(c))

But actually, that's not what I'm searching for.

Maybe someone can help me :)

Thank you

CodePudding user response:

You can use the tidyverse package for this. You transform your data into long-format that you get three variables: "names", "values" and "group". After that you can plot your boxplots with ggplot():

value_a <- rnorm(100, 0, 1)
value_b <- rnorm(100, 0, 1)
group <- as.factor(rbinom(100, 1, 0.5))

data <- data.frame(value_a,value_b,group)

library(tidyverse)

data %>%
  pivot_longer(value_a:value_b, names_to = "names", values_to = "values") %>%
  ggplot(aes(y = values, x = group, fill = names)) 
  geom_boxplot()

Created on 2022-08-19 with Grouped boxplot with base graphics

The at argument controls the grouping and placement of the boxes. Contrary to ggplot2 you need to choose placing manually, but you also get very fine control of spacing very easily.

Slightly refined version of the plot:

boxplot(values ~ ind   c, data = d, at = c(1, 2, 4, 5),
        col = c(2, 4), show.names = FALSE,
        xlab = "")
axis(1, labels= c("c = 0", "c = 1"), at = c(1.5, 4.5))
legend("topright", fill = c(2, 4), legend = c("a", "b"))

enter image description here

  • Related