Boxplots of four variables in the same plot

1.1k Views Asked by At

I would like to make four boxplots side-by-side using ggplot2, but I am struggling to find an explanation that suits my purposes.

I am using the well-known Iris dataset, and I simply want to make a chart that has boxplots of the values for sepal.length, sepal.width, petal.length, and petal.width all next to one another. These are all numerical values.

I feel like this should be really straightforward but I am struggling to figure this one out.

Any help would be appreciated.

3

There are 3 best solutions below

1
Allan Cameron On BEST ANSWER

This is a one-liner using reshape2::melt

ggplot(reshape2::melt(iris), aes(variable, value, fill = variable)) + geom_boxplot()

enter image description here

0
Duck On

Try this. The approach would be to selecting the numeric variables and with tidyverse functions reshape to long in order to sketch the desired plot. You can use facet_wrap() in order to create a matrix style plot or avoid it to have only one plot. Here the code (Two options):

library(tidyverse)
#Data
data("iris")
#Code
iris %>% select(-Species) %>%
  pivot_longer(everything()) %>%
  ggplot(aes(x=name,y=value,fill=name))+
  geom_boxplot()+
  facet_wrap(.~name,scale='free')

Output:

enter image description here

Or if you want all the data in one plot, you can avoid the facet_wrap() and use this:

#Code 2
iris %>% select(-Species) %>%
  pivot_longer(everything()) %>%
  ggplot(aes(x=name,y=value,fill=name))+
  geom_boxplot()

Output:

enter image description here

0
akrun On

In base R, it can be done more easily in a one-liner

boxplot(iris[-5])

enter image description here


Or using ggboxplot from ggpubr

library(ggpubr)
library(dplyr)
library(tidyr)
iris %>% 
  select(-Species) %>%
  pivot_longer(everything()) %>% 
  ggboxplot(x = 'name', fill = "name", y = 'value', 
      palette = c("#00AFBB", "#E7B800", "#FC4E07", "#00FABA"))

enter image description here