Home > Blockchain >  How to reduce the spacing in boxplot between groups using ggplot in R?
How to reduce the spacing in boxplot between groups using ggplot in R?

Time:09-17

I am trying to reduce the spacing in boxplot between groups without changing the boxplot width. Most solutions online are to adjust the distance within a sub-group, but not between groups. Thanks a lot!

library("ggplot2")
data(iris)                           # Example data
iris_new <- iris
iris_new$new <- letters[1:2]

ggplot(iris_new, aes(x = Species, y = Sepal.Length, fill = new))  
       geom_boxplot()

enter image description here

CodePudding user response:

Surprisingly, I can't find an exact duplicate for this question, so will post an answer here in case no-one else can find a duplicate either.

The answer lies in either increasing the width of your boxes (the default is 0.75, so increasing to 1 might work well for you):

ggplot(iris_new, aes(x = Species, y = Sepal.Length, fill = new))  
  geom_boxplot(width = 1)

enter image description here

or changing from the default position_dodge2 to position_dodge, with an increase in the width of the dodge (again the default is 0.75, so we can try increasing this to 1)

ggplot(iris_new, aes(x = Species, y = Sepal.Length, fill = new))  
  geom_boxplot(position = position_dodge(width = 1))

enter image description here

  • Related