[R] How to overlap two density plots?

Jared O'Connell jared.oconnell at gmail.com
Sat Apr 26 13:49:40 CEST 2008


Very näively, you could do something like this,

plot(density(A))
lines(density(B),col=2)

, and tinker your xlim and ylim as suitable.  The Cairo library gives
a pretty example,

data(iris)
attach(iris)
plot(Petal.Length, rep(-0.03,length(Species)), xlim=c(1,7),
          ylim=c(0,1.7), xlab="Petal.Length", ylab="Density",
          pch=21, cex=1.5, col="#00000001", main = "Iris (yet again)",
          bg=c("#ff000020","#00ff0020","#0000ff20")[unclass(Species)])
for (i in 1:3) polygon(density(Petal.Length[unclass(Species)==i],bw=0.2),col=c("#ff000040","#00ff0040","#0000ff40")[i])



More information about the R-help mailing list