9

I would like to plot violin plots where x axis is exon however I want to group the plots. This works if its just violins however when I add in the jitters for some reason its not responding the correct aes and is plotting on its own? Here is a reproducible code with a screen shot of the error. thanks!

set.seed(1)
df <- data.frame(
  exons = c(rep("e1", 200), rep("e2", 200)),
  values = rnorm(400, 200, 40),
  group = c(
    rep("g1", 75), rep("g2", 75), rep("g3", 50),
    rep("g1", 75), rep("g2", 75), rep("g3", 50)
  )
)

ggplot(df, aes(y = values, x = exons, fill = group)) +
  geom_violin() +
  geom_jitter(shape = 16, position = position_jitter(0.07))

so if the plot works the dots should had been plotted within each of the group for each exon, however here it is clearly not.

enter image description here

Tung
  • 26,371
  • 7
  • 91
  • 115
Ahdee
  • 4,679
  • 4
  • 34
  • 58

2 Answers2

8

You probably want both position_dodge() and position_jitterdodge()

library(ggplot2)
ggplot(df, aes(y = values, x = exons, fill = group)) +
  geom_violin(position = position_dodge(width = 0.9)) +
  geom_point(position = position_jitterdodge(seed = 1, dodge.width = 0.9))

Another option worth mentioning is geom_quasirandom() function from the ggbeeswarm package

library(ggbeeswarm)
ggplot(df, aes(y = values, x = exons, fill = group)) +
  geom_violin(position = position_dodge(width = 0.9)) +
  geom_quasirandom(dodge.width = 0.9, varwidth = TRUE)

Created on 2019-08-10 by the reprex package (v0.3.0)

Tung
  • 26,371
  • 7
  • 91
  • 115
  • Suggestion: use raincloud plot instead https://stackoverflow.com/questions/52630293/how-to-show-whiskers-and-points-on-violin-plots – Tung Jul 28 '20 at 19:38
0

Do you mean something like that?

set.seed ( 1)
df = data.frame ( 
  exons = c(rep("e1", 200), rep("e2", 200))
  ,values = rnorm(400,200,40)
  ,group = c(rep("g1", 75), rep("g2", 75), rep("g3",50),
             rep("g1", 75), rep("g2", 75), rep("g3",50) )
)

ggplot(df, aes(y= values  , x= exons , fill = group )) +
  geom_violin()+ 
  geom_jitter(shape=16, position=position_jitter(width = NULL, height = NULL))

You can define the degree of jitter in x and y direction.

stefx
  • 25
  • 10
  • Thats clever however not exactly since its not grouping correctly. I don't have a working example but pretty much the dots should jitter inside the violins. something like this. http://www.sthda.com/sthda/RDoc/figure/ggplot2/ggplot2-violin-plot-dot-plot-data-visualization-2.png – Ahdee Aug 10 '19 at 19:42