8

I have some data dt = data.table(x=c(1:200),y=rnorm(200)) and I start with a density plot using ggplot2:

plot = ggplot(dt,aes(y)) + geom_density(aes(y=..density..))

Is there a way I can add percentile lines similar to this?

If further I could shade the segments of the graph (created by the percentile lines) similar to this, then that would be great!

user1317221_G
  • 15,087
  • 3
  • 52
  • 78
user32259
  • 1,113
  • 3
  • 13
  • 21

2 Answers2

19

Here is a possibility heavily inspired by this answer :

dt <- data.table(x=c(1:200),y=rnorm(200))
dens <- density(dt$y)
df <- data.frame(x=dens$x, y=dens$y)
probs <- c(0.1, 0.25, 0.5, 0.75, 0.9)
quantiles <- quantile(dt$y, prob=probs)
df$quant <- factor(findInterval(df$x,quantiles))
ggplot(df, aes(x,y)) + geom_line() + geom_ribbon(aes(ymin=0, ymax=y, fill=quant)) + scale_x_continuous(breaks=quantiles) + scale_fill_brewer(guide="none")

enter image description here

Community
  • 1
  • 1
juba
  • 47,631
  • 14
  • 113
  • 118
8
myd = data.frame(xvar=rnorm(2000),yvar=rnorm(2000))

    xd <- data.frame(density(myd$xvar)[c("x", "y")])
    p <- ggplot(xd, aes(x, y)) + 

      geom_area(data = subset(xd, x < -1), fill = "pink") +
      geom_area(data = subset(xd, x < -1.96), fill = "red") +
      geom_area(data = subset(xd, x > 1), fill = "lightgreen") +
      geom_area(data = subset(xd, x > 1.96), fill = "green") +

      geom_line()

    p 

enter image description here

Seth
  • 4,745
  • 23
  • 27