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.
I have been able to plot my density curve with the following:
setwd("D:/Workspace")
# -- create dataframe
coursename <- c('Math','Math','Math','Math','Math')
value <- c(.12, .4, .5, .8, .9)
df <- data.frame(coursename, value)
library(ggplot2)
density_plot <- 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
I've tried using the following code to shade the area between .25 and .5:
x1 <- min(which(df$value >=.25))
x2 <- max(which(df$value <=.5))
with(density_plot, polygon(x=c(x[c(x1,x1:x2,x2)]), y=c(0, y[x1:x2], 0), col="gray"))
But it just generates the following error:
Error in xy.coords(x, y) : object 'y' not found
y
isn't found since you referencey[x1:x2]
in the call topolygon
(and there is noy
); (2) you're trying to mix ggplot2/grid and base graphics. – hrbrmstr