title: How to shade specific region under ggplot2 density curve?
body: <p><a href="https://stackoverflow.com/questions/3494593/shading-a-kernel-density-plot-between-two-points">Related post here</a></p>
  
  <p>My intention is to shade area an area underneath the density curve that lie between two points. In this example, I would like to shade the areas between the values .25 and .5. </p>
  
  <p>I have been able to plot my density curve with the following:</p>
  
  <pre><code>    setwd("D:/Workspace")
  
      # -- create dataframe
  
      coursename &lt;- c('Math','Math','Math','Math','Math')
      value &lt;- c(.12, .4, .5, .8, .9)
      df &lt;- data.frame(coursename, value)
  
      library(ggplot2)
  
      density_plot &lt;- ggplot(aes(x=value, colour=coursename, fill=coursename), data=df) +
                        geom_density(alpha=.3) +
                        geom_vline(aes(xintercept=.5), colour="blue", data=df, linetype="dashed", size=1) +
                        scale_x_continuous(breaks=c(0, .25, .5, .75, 1), labels=c("0", ".25", ".5", ".75", "1")) +
                        coord_cartesian(xlim = c(0.01, 1.01)) +
                        theme(axis.title.y=element_blank(), axis.text.y=element_blank()) +
                        ggtitle("sample data")
  
      density_plot
  </code></pre>
  
  <p>I've tried using the following code to shade the area between .25 and .5:</p>
  
  <pre><code>    x1 &lt;- min(which(df$value &gt;=.25))
      x2 &lt;- max(which(df$value &lt;=.5))
  
      with(density_plot, polygon(x=c(x[c(x1,x1:x2,x2)]), y=c(0, y[x1:x2], 0), col="gray"))
  </code></pre>
  
  <p>But it just generates the following error:</p>
  
  <pre><code>Error in xy.coords(x, y) : object 'y' not found
  </code></pre>