Search code examples
rlinegraphing

R Density Graph: How can I add a solid line from the x-axis to the top of the density curve


I have a density plot graphed using:

plot(density(x))

What I am interested in doing is creating a line for something like x = 5 from the x-axis to the corresponding spot on the curve.

Like this:

example


Solution

  • You can do this by first storing the density values in an object, and then retrieving the x and y elements from this object. In the following example I use findInterval to retrieve the y-value for the given x-value:

    x <- rnorm(1000) # Sample data
    y <- density(x)  # Calculate and store density
    
    x0 <- 2 # Desired position on x-axis
    y0 <- y$y[findInterval(x0, y$x)] # Corresponding y value
    
    plot(density(x))
    segments(x0, 0, x0, y0)
    

    enter image description here