Cbhihe - 13 days ago 9x
R Question

# How to insert a legend in density plot with qplot in R

I am completely new to R, and want to insert a simple colored box legend identifying each distribution as "data.1" and "data.2", in the following

`qplot`
plotting function (from the
`ggplot2`
package):

``````> V1 <- matrix(unlist(rnorm(200,-0.2,1)))
> V2 <- matrix(unlist(rnorm(200,0.3,4)))
> m <- data.frame(V1,V2)
> qplot(V1, main="Observed distr.", data=m,
geom='density',xlab="x",ylab="count",fill=I('green'), alpha=I(.5)) +
geom_density(aes(V2),data=m,fill='red', alpha=I(.5))
``````

I have found solutions for
`ggplot`
but nothing for
`qplot`
with
`geom='density'`
. The curves are well drawn but no legend appears.

I would accept any solution that gives me a density plot with transparency, labelled axes, a title and a colored box legend. Thank you.

As someone put it "ggplot likes data in the 'long' format: i.e., a column for every dimension, and a row for every observation". So we `melt` the `data.frame`

``````require(ggplot2)
require(data.table)
set.seed(10) # this is so you get the same numbers from rnorm.
m <- data.frame(V1 = matrix(unlist(rnorm(200, -0.2, 1))),
V2 = matrix(unlist(rnorm(200, 0.3, 4))))

m <- melt(m) # This comes from data.table, yet, many alt. ways to achieve this