Shade density plot to the left of vline?

2019-06-26 02:17发布

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)

标签: r ggplot2
1条回答
何必那么认真
2楼-- · 2019-06-26 02:26

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

查看更多
登录 后发表回答