RandomThinker
RandomThinker

Reputation: 391

Overlaying Density Plots

I have three sets of data (df$A, df$B, df$C) and I want to plot the density plots for them (the frequency of each value). I know I can achieve it using plot(density(df$A)).

However, I want to put three density plots in one plot and let the density plots of df$B and df$C serve as the confidence interval band for the density plot of df$A. That is, preferably, the density plots of df$B and df$C can be in lighter colors or even dotted lines.

Upvotes: 1

Views: 91

Answers (1)

dcarlson
dcarlson

Reputation: 11076

This may be close to what you want to do. First we need some data. Since you mention confidence limits, I will place the means for the second and third densities at 2 standard deviations on either side of the mean of the first density with half the standard deviation of the first density:

set.seed(42)
A <- rnorm(100, 50, 10)
B <- rnorm(100, 30, 5)
C <- rnorm(100, 70, 5)
df <- data.frame(A, B, C)

Next the densities:

Ad <- density(df$A)
Bd <- density(df$B)
Cd <- density(df$C)

Now we need to know the x and y limits for the plot:

xr <- range(c(Ad$x, Bd$x, Cd$x))
yr <- range(c(Ad$y, Bd$y, Cd$y))

Finally the plot:

plot(Ad, xlim=xr, ylim=yr)
lines(Bd, lty=3)
lines(Cd, lty=3)

Density Plot

Upvotes: 2

Related Questions