Change Spaces Between Grouped Boxplots in R (2 Examples)

In this article, I’ll explain how to adjust the spaces between ggplot2 boxplot groups in R.

Setting up the Examples

data(iris)                           # Example data
iris_new <- iris
iris_new$new <- letters[1:2]
head(iris_new)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species new
# 1          5.1         3.5          1.4         0.2  setosa   a
# 2          4.9         3.0          1.4         0.2  setosa   b
# 3          4.7         3.2          1.3         0.2  setosa   a
# 4          4.6         3.1          1.5         0.2  setosa   b
# 5          5.0         3.6          1.4         0.2  setosa   a
# 6          5.4         3.9          1.7         0.4  setosa   b
install.packages("ggplot2")          # Install & load ggplot2
library("ggplot2")
ggplot(iris_new,                     # Default ggplot2 boxplot
       aes(x = Species,
           y = Sepal.Length,
           fill = new)) +
  geom_boxplot()

r graph figure 1 change spaces between grouped boxplots r

Example 1: Same Space Between All Boxes

ggplot(iris_new,                     # Equal space
       aes(x = Species,
           y = Sepal.Length,
           fill = new)) +
  geom_boxplot(position = position_dodge(1))

r graph figure 2 change spaces between grouped boxplots r

Example 2: Avoid Space Between Boxplot Groups

ggplot(iris_new,                     # No space
       aes(x = Species,
           y = Sepal.Length,
           fill = new)) +
  geom_boxplot(position = "dodge")

r graph figure 3 change spaces between grouped boxplots r

Related Tutorials & Further Resources

You may find some related R programming language tutorials on topics such as graphics in R and ggplot2 in the following list:

Leave a Reply

Your email address will not be published. Required fields are marked *

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