Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shade density plot to the left of vline?

Tags:

r

ggplot2

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)
like image 291
Ignacio Avatar asked Mar 25 '16 16:03

Ignacio


1 Answers

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:

set.seed(4132)
df.plot <- data.frame(density=rnorm(100))
ds <- density(df.plot$density, from = min(df.plot$density), to = -0.25)
ds_data <- data.frame(x = ds$x, y = ds$y)

density() estimates the density for the points given in its first argument. The result will contain x and y values. You can specify the x-range you are interested in with from and to. In order for the density to agree with the one plotted by ggplot(), set the ranges to the minimal and maximal value in df.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 the x and y values with ds$x and ds$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:

library(ggplot2)
ggplot(df.plot, aes(density)) + geom_density() + 
  geom_vline(xintercept = -0.25) +
  geom_area(data = ds_data, aes(x = x, y = y))

enter image description here

like image 67
Stibu Avatar answered Oct 02 '22 06:10

Stibu