ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

alignment problem with preserve = "single" and preserve = "total"

Open ThomasKraft opened this issue 4 years ago • 5 comments

This issue is a follow-up on https://github.com/tidyverse/ggplot2/issues/2712#issue-335176790.

The previously posted solution does not work when there are 3 grouping levels, in which case the geom_point and geom_boxplot layers no longer match up again.

Reprex:

mtcars2 <- bind_rows(mtcars, data.frame(gear = c(4,5), mpg = c(22, 19), am = c(2, 2)))
ggplot(mtcars2, aes(factor(gear), mpg, fill = factor(am))) + 
   geom_boxplot(position = position_dodge2(0.75, preserve = 'single')) +
   geom_point(position = position_dodge(0.75, preserve = 'total'))

ThomasKraft avatar Feb 18 '21 19:02 ThomasKraft

Running the reprex:

library(tidyverse)

mtcars2 <- bind_rows(mtcars, data.frame(gear = c(4,5), mpg = c(22, 19), am = c(2, 2)))
ggplot(mtcars2, aes(factor(gear), mpg, fill = factor(am))) + 
  geom_boxplot(position = position_dodge2(0.75, preserve = 'single')) +
  geom_point(position = position_dodge(0.75, preserve = 'total'))

Created on 2021-02-18 by the reprex package (v1.0.0)

Is #2801 related?

clauswilke avatar Feb 18 '21 20:02 clauswilke

That does seem to be a related issue -- was there a workaround to implement that solution prior to the commit which fixed the issue?

ThomasKraft avatar Feb 18 '21 20:02 ThomasKraft

Is this the same issue as #3647?

javlon avatar Aug 13 '22 21:08 javlon

Above PR solves the current bug. But it's not a good solution because future changes in the position selection algorithm in one of the position_dodge() and position_dodge2 functions might lead to the same misalignment problem.

Following script reproduces the same problem as in this issue and #3647:

library(tidyverse)
set.seed(42)

df <- bind_rows(lapply(1:7, function(i) {
  data.frame(
    x = i,
    y = rnorm(10*i),
    g = sample(LETTERS[seq_len(i)], 10*i, replace = T)
  )
}))

ggplot(df, aes(as.factor(x), y, fill = g)) +
  geom_boxplot(position = position_dodge2(0.75, preserve = "single")) +
  geom_point(position = position_dodge(0.75, preserve = "total"), shape = 4)+
  xlab("number of groups")

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

And the plot generated by the above PR fixes the misalignment problem.

javlon avatar Aug 14 '22 11:08 javlon

in your plot, the position of the boxplots has changed from before and the distance between the boxplots depends on the n of groups not sure this will be a desirable visual change

smouksassi avatar Aug 14 '22 12:08 smouksassi