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 |
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") |
install.packages("ggplot2") # Install & load ggplot2 library("ggplot2")
ggplot(iris_new, # Default ggplot2 boxplot aes(x = Species, y = Sepal.Length, fill = new)) + geom_boxplot() |
ggplot(iris_new, # Default ggplot2 boxplot aes(x = Species, y = Sepal.Length, fill = new)) + geom_boxplot()
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)) |
ggplot(iris_new, # Equal space aes(x = Species, y = Sepal.Length, fill = new)) + geom_boxplot(position = position_dodge(1))
Example 2: Avoid Space Between Boxplot Groups
ggplot(iris_new, # No space aes(x = Species, y = Sepal.Length, fill = new)) + geom_boxplot(position = "dodge") |
ggplot(iris_new, # No space aes(x = Species, y = Sepal.Length, fill = new)) + geom_boxplot(position = "dodge")
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: