ToNoY
ToNoY

Reputation: 1378

Kernel density plots on a single figure

I have been trying to plot simple density plots using R as:

plot(density(Data$X1),col="red")
plot(density(Data$X2),col="green")

Since I want to compare, I'd like to plot both in one figure. But 'matplot' doesn't work!! I also tried with ggplot2 as:

library(ggplot2)
qplot(Data$X1, geom="density")
qplot(Data$X2, add = TRUE, geom="density")

Also in this case, plots appear separately (though I wrote add=TRUE)!! Can anyone come up with an easy solution to the problem, please?

Upvotes: 2

Views: 3293

Answers (4)

agstudy
agstudy

Reputation: 121568

In ggplot2 or lattice you need to reshape the data to seupose them.

For example :

    dat <- data.frame(X1= rnorm(100),X2=rbeta(100,1,1))
    library(reshape2)
    dat.m <- melt(dat)

Using ``lattice`

  densityplot(~value , groups = variable, data=dat.m,auto.key = T)

enter image description here

Using ``ggplot2`

 ggplot(data=dat.m)+geom_density(aes(x=value, color=variable))

enter image description here EDIT add X1+X2

Using lattice and the extended formua interface, it is extremely easy to do this:

densityplot(~X1+X2+I(X1+X2) , data=dat)   ## no need to reshape data!!

enter image description here

Upvotes: 3

Greg Snow
Greg Snow

Reputation: 49640

If you specify n, from, and to in the calls to density and make sure that they match between the 2 calls then you should be able to use matplot to plot both in one step (you will need to bind the 2 sets of y values into a single matrix).

Upvotes: 0

harkmug
harkmug

Reputation: 2785

You can try:

plot(density(Data$X1),col="red")

points(density(Data$X2),col="green")

I must add that the xlim and ylim values should ideally be set to include ranges of both X1 and X2, which could be done as follows:

foo <- density(Data$X1)

bar <- density(Data$X2)

plot(foo,col="red", xlim=c(min(foo$x,bar$x),max(foo$x,bar$x)) ylim=c(min(foo$y,bar$y),max(foo$y,bar$y))

points(bar,col="green")

Upvotes: 3

IRTFM
IRTFM

Reputation: 263342

In base graphics you can overlay density plots if you keep the ranges identical and use par(new=TRUE) between them. I think add=TRUE is a base graphics strategy that some functions but not all will honor.

Upvotes: 1

Related Questions