Home > Net >  Increasing space between boxplot-groups in R
Increasing space between boxplot-groups in R

Time:06-07

I think it is probably quite simple to solve, however, I do not manage to change the distance between two groups in grouped boxplots.

v1 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2)
v2 <- c(0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2)
v3 <- c(13,67,89,280,40,1,23,99,32,1,75,280,270,200,196,300,320, 277,23,4,1,2,5,89,45,23,11,1,3,23,43,90,1,7,250,200,100,11,6,6,123,12, 86,11,300,299,320,190,170,150,344,244,123,234,45)

summary <- data.frame(v1, v2, v3)

summary$v1 <- as.factor(summary$v1)
summary$v2 <- as.factor(summary$v2)

ggplot(summary, aes(x = v1, y = v3, fill = v2))   geom_boxplot(width = 1, size = 0.4)   geom_dotplot(aes(fill = v2), binaxis='y',  stackdir='center', binwidth=5, position = position_dodge(1))

I created a figure with arrows showing where I want to add some more space between groups. Thanks in advance for your help.

[boxplot example][1]: https://i.stack.imgur.com/UHcLn.png

CodePudding user response:

You'd need to change your width to something <1 to allow for the dodge positioning to do its work (and add some dodge positioning to the box plot geom as well).

E.g.

summary |>
  ggplot(aes(x    = v1,
             y    = v3,
             fill = v2))  
  geom_boxplot(width    = 0.5,
               position = position_dodge(0.6))  
  geom_dotplot(binaxis  = "y", 
               stackdir = "center",
               binwidth = 5,
               position = position_dodge(0.6))

enter image description here

CodePudding user response:

You could use facet_wrap with scales = "free_x":

(The addition of the theme will remove the strip headings if preferred.)

library(tidyverse)

v1 <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
v2 <- c(0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
v3 <- c(13, 67, 89, 280, 40, 1, 23, 99, 32, 1, 75, 280, 270, 200, 196, 300, 320, 277, 23, 4, 1, 2, 5, 89, 45, 23, 11, 1, 3, 23, 43, 90, 1, 7, 250, 200, 100, 11, 6, 6, 123, 12, 86, 11, 300, 299, 320, 190, 170, 150, 344, 244, 123, 234, 45)

summary <- data.frame(v1, v2, v3)

summary$v1 <- as.factor(summary$v1)
summary$v2 <- as.factor(summary$v2)

ggplot(summary, aes(v1, v3, fill = v2))  
  geom_boxplot(width = 1, size = 0.4)  
  geom_dotplot(binaxis = "y", stackdir = "center", 
               binwidth = 5, position = position_dodge(1))  
  facet_wrap(~ v1, scales = "free_x")   
  theme(
    strip.background = element_blank(),
    strip.text.x = element_blank()
  )

Created on 2022-06-06 by the reprex package (v2.0.1)

  • Related