0
votes

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
This reminds me of one of my very first questions: Do I really need to reshape this wide data to use ggplot2?. The answer, essentially, is yes: ggplot works really well with long data, and if your data is wide, your first step is to make it long. tidyr::pivot_longer is a good tool for that job.Gregor Thomas

3 Answers

1
votes

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
votes

This is a one-liner using reshape2::melt

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

enter image description here

0
votes

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