Adjust Width & Position of Specific ggplot2 Boxplot in R (2 Examples)

In this R tutorial you’ll learn how to adjust the width and position of a specific boxplot in a grouped ggplot2 boxplot.

Preparing the Examples

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

r graph figure 1 adjust width position specific ggplot2 boxplot r

Example 1: Apply position_dodge2() Function Change to change Width of Grouped ggplot2 Boxplot

ggplot(iris_new,                     # Change width
       aes(x = Species,
           y = Petal.Width,
           fill = subgroup)) +
  geom_boxplot(position = position_dodge2(preserve = "single"))

r graph figure 2 adjust width position specific ggplot2 boxplot r

Example 2: Apply position_dodge2() Function Change to change Location of Grouped ggplot2 Boxplot

ggplot(iris_new,                     # Change position
       aes(x = Species,
           y = Petal.Width,
           fill = subgroup)) +
  geom_boxplot(position = position_dodge(preserve = "single"))

r graph figure 3 adjust width position specific ggplot2 boxplot r

Related Tutorials

Below, you can find some further resources that are related to the content of this article.

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