2

Consider the graph below given by this code:

require(ggplot2)
my_data<-c(70,  71, 75, 78, 78, 79, 80, 81, 84, 85, 87, 87, 90, 91, 95, 95, 96, 96, 97, 98, 98, 100,    101,    102,    102,    102,    102,    104,    104,    104,    107,    107,    109,    110,    110,    110,    111,    112,    113,    113,    114,    115,    118,    118,    118,    120,    124,    131,    137,    137,    139,    145,    158,    160,    162,    165,    169,    177,    179,    180)    


qplot(my_data,dist, geom="line")+xlab("x values")+ylab("Density")+
geom_point()+
ggtitle("cool graph Distribution") + 
geom_line(color="black", size=0.1) +
geom_line(stat = "vline", xintercept = "mean", colour = "red", size=1.1)

the resulted graph looks like this: enter image description here

My objective is to add another blue line to the graph that:

  1. Intersect with the curve
  2. Show the value on the X axis
  3. Add a title on top of it

to visualize it, it should look like this: enter image description here

I know how to add a geom_line but it goes bottom-up, I wish for 'one point intersection' with the curve.

adhg
  • 10,437
  • 12
  • 58
  • 94
  • possible duplicate of [Adding vertical line in plot ggplot](http://stackoverflow.com/questions/19622063/adding-vertical-line-in-plot-ggplot) – Scransom May 07 '15 at 04:22
  • 2
    Disagree about the duplicate: those answers use `geom_vline` which wouldn't work for this question. (OP wants a line that only goes from y = 0 to the distribution line, not all the way to the top of the graph.) There probably are other duplicates, but the one linked above isn't a good match. – Gregor Thomas May 07 '15 at 15:41

1 Answers1

7

It's really more or less the same. I prefer to use annotate for things like this. (I'd do your red line with annotate as well, personally.) Just calculate where you want things to go and add them to the plot:

qplot(my_data,dist, geom="line")+xlab("x values")+ylab("Density")+
    geom_point()+
    ggtitle("cool graph Distribution") + 
    geom_line(color="black", size=0.1) +
    geom_line(stat = "vline", xintercept = "mean", colour = "red", size=1.1) +
    annotate(geom = "segment", x = 98, xend = 98, y = 0,
             yend = dnorm(98, mean = mean(my_data), sd = sd(my_data)),
             color = "blue") +
    annotate(geom = "text", x = 98, y = -.02 * max(dist), label = "98")

I'll leave the title at the top as an "exercise for the reader", it should be pretty straightforward based on the pieces that are there already.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294