5

I was wondering how to connect vertical lines from individual subject data points to a horizontal line. My main issue is that the x-axis is grouped and does not have a continuous variable to specify the position of the line. If I make the line come down from the group (xend), I just end up with 1 vertical line for each group.

Here is what I currently have

without vertical lines

ggplot() +
geom_point(data = df, aes(x = Group, y = Number, color = Group), position = "jitter") +
geom_hline(yintercept = 33.25)

If I add

  geom_segment(data = df, 
           aes(x=Group, 
               xend=Group, 
               y=Number, 
               yend=33.25))

I end up with the one vertical line per group, rather than stemming from each subject

atamalu
  • 63
  • 1
  • 8

1 Answers1

6

Good news is that the upcoming version of ggplot2 provides reproducible jitter. Bad news is that geom_segment() doesn't allow jitter, so use geom_linerange() instead.

We will be able to specify seed like bellow. Hope the version will be released soon! In the meantime, you should manually add jitter to the data as answered on https://stackoverflow.com/a/21922792/5397672.


reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-12

library(ggplot2)

set.seed(2)
dat <-  iris[sample(1:nrow(iris), 20),]

ggplot(dat, aes(x=Species, y=Petal.Width)) +
  geom_point(position = position_jitter(height = 0L, seed = 1L)) +
  geom_hline(yintercept=0.75) +
  geom_linerange(aes(x=Species, ymax=Petal.Width, ymin=0.75),
                 position = position_jitter(height = 0L, seed = 1L))

yutannihilation
  • 798
  • 4
  • 9