1

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.

RandomThinker
  • 391
  • 1
  • 6
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jun 17 '21 at 17:26

1 Answers1

2

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

dcarlson
  • 10,936
  • 2
  • 15
  • 18