ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

preserve = "single" breaks violin plots

Open willgearty opened this issue 7 years ago • 1 comments

I'm trying to use preserve = "single" as you would with boxplots to maintain the sizes of the boxes when there are unused factors. While I figured it would work just the same way for violin plots, it appears to completely break them.

p <- ggplot(mtcars, aes(factor(cyl), mpg))
#works fine
p + geom_violin(aes(fill = factor(vs)))
#works fine
p + geom_violin(aes(fill = factor(vs)), position = "dodge")
#this doesn't work
p + geom_violin(aes(fill = factor(vs)), position = position_dodge(preserve = "single"))

The latter attempt above produces this:

image

willgearty avatar Aug 03 '18 21:08 willgearty

The problem is that position_dodge() tries to find the maximum number of groups by counting the maximum number of rows in the data with the same xmin value: https://github.com/tidyverse/ggplot2/blob/4d2ca992dc37fee598d83d3d3f524dbba38f4187/R/position-dodge.r#L100-L101 This works for boxplots, because each boxplot is one line in the processed data. But it doesn't work for violin plots, because each violin plot consists of many lines (512 by default). I suspect the solution would be to count the number of identical xmin values with distinct group values.

clauswilke avatar Aug 08 '18 15:08 clauswilke