0

I'm trying to plot a ggplot bar plot with geom_jitter over the top so as to get a better visualisation on the variation in my measure. The code is as follows:

ggplot(data) +
   geom_bar(stat="summary", fun.y="mean", aes(x=cohort, y=., fill=time), position="dodge") +
   geom_jitter(aes(x=cohort, y=., colour=time), size=0.5)

The geom_bar is grouped with colour and position="dodge" so as to get the bars side by side, but geom_jitter doesn't recognise the position="dodge" argument, so the points are evenly scattered across the whole width of the two colour columns, as follows (obviously the colours aren't good like this, I've simplified the code to the crucial bit):

enter image description here

How can I make the geom_jitter line up with the columns of the geom_bar?

If you want to try and reproduce this, data is set up essentially like this:

data <- read.table(header=TRUE, text='
subj cohort time .
   1      EL1 t1 0.433
   2      EL1 t1 0.545
   3      EL1 t1 0.698
   4      EL1 t1 0.224
   5      EL1 t1 0.463
   6      HL1 t1 0.211
   7      HL1 t1 0.702
   8      HL1 t1 0.310
   9      HL1 t1 0.822
   10     EL1 t1 0.0
   11     EL1 t1 0.544
   12     EL1 t1 0.234
   13     EL1 t1 0.492
   14     HL1 t2 0.234
   15     HL1 t2 0.755
   16     HL1 t2 0.321
   17     HL1 t2 0.600
   18     EL1 t2 0.0
   19     EL1 t2 0.522
   20     EL1 t2 0.624
   21     EL1 t2 0.239
   22     EL1 t2 0.474
   23     HL1 t2 0.293
   24     HL1 t2 0.599
   25     HL1 t2 0.310
   26     HL1 t2 0.411
')
Henry Brice
  • 280
  • 1
  • 2
  • 18
  • It seems that you also posted identical question [here](https://datascience.stackexchange.com/questions/46478/ggplot-geom-jitter-dodge-position) – pogibas Mar 01 '19 at 18:52
  • Yes, is it considered bad to post the same question in two fora? It seemed relevant to ask both communities. I'll remove one if it's not appropriate... – Henry Brice Mar 04 '19 at 17:44

1 Answers1

2

Rather than going with geom_jitter (which is just a shorthand for geom_point(position="jitter"), you can use geom_point(position=position_jitterdodge()) This will allow to have both jitter and dodge at once

ggplot(data) +
  geom_bar(stat="summary", fun.y="mean", aes(x=cohort, y=., fill=time), position="dodge") +
  geom_point(aes(x=cohort, y=., colour=time), size=0.5, position=position_jitterdodge())

Which gives the requested output: enter image description here

Henry Brice
  • 280
  • 1
  • 2
  • 18