R How to Plot Multiple Boxplots in the Same Graphic (Example Code)

This tutorial explains how to plot several boxplots side-by-side in the same graphic in the R programming language.

Preparing the Example

We’ll use this data frame for the example:

set.seed(65434)                            # Set random seed
my_df <- data.frame(values = rnorm(90),    # Create example data
                    variable = c(rep("V1", 30), rep("V2", 30), rep("V3", 30)),
                    group = c("G1", "G2"))
head(my_df)                                # Return head of example data
#       values variable group
# 1  0.6551126       V1    G1
# 2  1.8020204       V1    G2
# 3 -0.5536936       V1    G1
# 4  0.2671233       V1    G2
# 5 -2.0112848       V1    G1
# 6  0.6543713       V1    G2

Example: Draw Multiple Boxplots Side-by-Side Using ggplot2 Package

install.packages("ggplot2")                # Install ggplot2 package
library("ggplot2")                         # Load ggplot2
ggplot(my_df, aes(x = variable,            # Applying ggplot function
                  y = values,
                  color = group)) +
  geom_boxplot()

r graph figure 1 r multiple boxplots same graphic

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top