Search code examples
rggplot2density-plotviolin-plotggforce

How to keep coloured geom_sina points within geom_violin plots?


I succeeded to jitter points in violins by combining geom_violin and geom_sina (left plot in the figure above), but when I try to color the points, they are jittered on several columns outside the violins (right plot in figure above).

enter image description here

What I would like to get is the left plot with colored points (I do not care if they are mixed (I mean not grouped by color).

Here is a demo script using mtcars dataset (I do not know mtcars dataset in detail, then apologize if I did some crazy use of the variables).

library(ggplot2)  
library(ggforce)

data(mtcars)

p <- ggplot(mtcars, aes(x=factor(vs), y=mpg)) + geom_violin()

p + geom_sina(alpha = 0.5)
p + geom_sina(aes(colour = factor(cyl)), alpha = 0.5)

Solution

  • Thanks to teunbrand.

    p + geom_sina(aes(colour = factor(cyl), group = factor(vs)), alpha = 0.5)
    

    makes it.