1
votes

Here is my problem, I would like to display two density curves in R on the same plot with legends for lines.

So far I did manage to display 2 density curves on the same plot

require(ggplot2)
a = rnorm(1000, 20, 2)
b = rnorm(3000, 25, 2)

p = ggplot()
p = p + geom_density(col="red", aes(x=a))
p = p + geom_density(col="blue", aes(x=b))
p

This code give me what I want, but without the legend : I would like to have something that indicate what mean the red line, and what mean the blue one.

How could I do that ?

1

1 Answers

1
votes

One approach is to combine the two series into a data.frame (which can be done inline, as below), adding a column that will be used in the legend:

p <- ggplot(
  rbind(
    data.frame(x=a,type="a"),
    data.frame(x=b,type="b")),
  aes(x=x,color=type))+
  geom_density()+
  scale_color_manual(
    values = c(
      "a" = "red",
      "b" = "blue"))

enter image description here


Data:

require(ggplot2)
a = rnorm(1000, 20, 2)
b = rnorm(3000, 25, 2)