Is it possible to shade a density plot using a vline as cutoff? For example:
df.plot <- data.frame(density=rnorm(100))
library(ggplot2)
ggplot(df.plot, aes(density)) + geom_density() +
geom_vline(xintercept = -0.25)
I tried creating a new variable, but it does not work as I expected
df.plot <- df.plot %>% mutate(color=ifelse(density<(-0.25),"red","NULL"))
ggplot(df.plot, aes(density, fill = color, colour = color)) + geom_density() +
geom_vline(xintercept = -0.25)
I don't know of a way to do that directly with
ggplot
. But you could calculate the density outside of ggplot over the desired range:density()
estimates the density for the points given in its first argument. The result will containx
andy
values. You can specify thex
-range you are interested in withfrom
andto
. In order for the density to agree with the one plotted byggplot()
, set the ranges to the minimal and maximal value indf.plot$density
. Here,to
is set to-0.25
, because you only want the part of the density curve to the left of your vline. You can then extract thex
andy
values withds$x
andds$y
.The plot is then created by using the same code as you did, but adding an additional
geom_area()
with the density data that was calculated above: