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!
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.
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.
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.
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With