tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.5k stars 2.02k forks source link

Aligning geoms with preserve = "single" appears impossible #2712

Closed Ax3man closed 6 years ago

Ax3man commented 6 years ago

I want to plot a geom without with together with a geom that does have width, e.g. points and boxplots.

Not all factor combinations are present.

The default of adjusting the width (preserve = 'total') works fine. But when maintaining the box widths with preserve = 'single' I can no longer do the same for the points.

library(ggplot2)

ggplot(mtcars, aes(factor(gear), mpg, fill = factor(am))) + 
  geom_boxplot(position = position_dodge(preserve = 'total')) +
  geom_point(position = position_dodge(0.75, preserve = 'total'))


ggplot(mtcars, aes(factor(gear), mpg, fill = factor(am))) + 
  geom_boxplot(position = position_dodge(preserve = 'single')) +
  geom_point(position = position_dodge(0.75, preserve = 'total'))


ggplot(mtcars, aes(factor(gear), mpg, fill = factor(am))) + 
  geom_boxplot(position = position_dodge(preserve = 'single')) +
  geom_point(position = position_dodge(0.75, preserve = 'single'))
#> Warning in max(table(panel$xmin)): no non-missing arguments to max;
#> returning -Inf

Created on 2018-06-24 by the reprex package (v0.2.0).

batpigandme commented 6 years ago

I don't think this (below) is what you're going for, but you might want to try playing around with position_dodge2().

library(ggplot2)

ggplot(mtcars, aes(factor(gear), mpg, fill = factor(am))) + 
  geom_boxplot(position = position_dodge2(0.75, preserve = 'single')) +
  geom_point(position = position_dodge2(0.75, preserve = 'single'))

Created on 2018-06-24 by the reprex package (v0.2.0).

Ax3man commented 6 years ago

Yes ok, this solves it:

ggplot(mtcars, 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'))

rplot08

I didn't expect that one needs to pass different positions to the two geoms for them to line up, but I guess it makes sense to always use dodge2 for geoms that have width and dodge for geoms that don't.

lock[bot] commented 5 years ago

This old issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with reprex) and link to this issue. https://reprex.tidyverse.org/