Search code examples
rgraphggplot2normal-distributiongplots

How to add a sample vertical line to in a gplot?


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.


Solution

  • 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.