eclarke / ggbeeswarm

Column scatter / beeswarm-style plots in ggplot2
GNU General Public License v3.0
539 stars 31 forks source link

It fails to show any beeswarm if axes are swapped #68

Closed holgerbrandl closed 1 year ago

holgerbrandl commented 2 years ago

Ggplot allows since some versions (3.0 I think) to swap x and y in geoms such geom_barchart or geom_bar. Unfortunately, when using geom_quasirandom as an overlay it does not work as expected.

Here're 2 versions of the same chart but with flipped mappings (in aes()). the boxplots are fine, but the geom_quasirandom overlay does not rotate correctly. image

image

I, unfortunately, can't share the source of the plot above, but if the problem is not clear, I could also work out a reprex.

csdaw commented 2 years ago

It's slightly difficult without a reprex but I'll try to help.

You've got 2 options.

  1. Use the groupOnX argument in geom_quasirandom()
  2. Use ggplot2::coord_flip() and don't swap x and y
library(ggplot2)
library(ggbeeswarm)

# produces a warning and doesn't swarm properly
ggplot(ToothGrowth, aes(y = factor(dose), x = len)) + 
  geom_boxplot() + 
  ggbeeswarm::geom_quasirandom()
#> Warning in f(...): The default behavior of beeswarm has changed in version
#> 0.6.0. In versions <0.6.0, this plot would have been dodged on the y-axis. In
#> versions >=0.6.0, grouponX=FALSE must be explicitly set to group on y-axis.
#> Please set grouponX=TRUE/FALSE to avoid this warning and ensure proper axis
#> choice.

# option 1: use groupOnX argument
ggplot(ToothGrowth, aes(y = factor(dose), x = len)) + 
  geom_boxplot() + 
  ggbeeswarm::geom_quasirandom(groupOnX = FALSE)

# option 2: use coord_flip() and don't swap x and y
ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  geom_boxplot() + 
  ggbeeswarm::geom_quasirandom() + 
  coord_flip()

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

holgerbrandl commented 2 years ago

Thanks @csdaw for your kind answer and for working out the reprex.

Regarding groupOnX. That's a great workaround, thanks for sharing! I still feel that this ticket describes a bug that might want to be fixed, because geom_quasirandom is not behaving correctly when the factor is on the y. Maybe it could simply set groupOnX in such a case under the hood?

Regarding coord_flip. It always had its limitations, which was - I think - also realized by the authors of ggplot. That's why they reworked the engine to allow the user to express her intent more clearly. To me coord_flip is now bad practice, which I don't teach anymore.

csdaw commented 2 years ago

No worries @holgerbrandl. I agree completely and I've already solved this problem in PR #63 but I'll need @eclarke to merge it to master before it's incorporated into the ggbeeswarm development version.