Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding percentile lines to a density plot [duplicate]

Tags:

r

ggplot2

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!

like image 877
user32259 Avatar asked Feb 13 '13 21:02

user32259


People also ask

How do you overlay two density plots?

Overlaying two density plots may seem complex, but it is as simple as plotting a same density graph. For every other plot you just have to keep calling the function with their respective density and add their required mechanism to functions except the first one to keep drawing them on the same plot.

Is density plot same as histogram?

By using a histogram we can represent a large amount of data, and its frequency. Density Plot is the continuous and smoothed version of the Histogram estimated from the data. It is estimated through Kernel Density Estimation.

What is a scaled density plot?

A density plot is a representation of the distribution of a numeric variable. It uses a kernel density estimate to show the probability density function of the variable (see more). It is a smoothed version of the histogram and is used in the same concept.


2 Answers

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

like image 91
juba Avatar answered Oct 21 '22 11:10

juba


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

like image 34
Seth Avatar answered Oct 21 '22 12:10

Seth