Shade density plot to the left of vline?

前端 未结 1 884
萌比男神i
萌比男神i 2021-01-13 06:14

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, ae         


        
1条回答
  •  死守一世寂寞
    2021-01-13 06:42

    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))
    

    0 讨论(0)
提交回复
热议问题