0
vec1 <- data.frame(x=rnorm(30))
vec2 <- data.frame(x=rnorm(100))
vec3 <- data.frame(x=rnorm(180))

ggplot() + 
geom_density(aes(x=x), linetype="solid", data=vec1) +
geom_density(aes(x=x), linetype="dashed", data=vec2) +
geom_density(aes(x=x), linetype="dotted", data=vec3) + 
scale_linetype_manual(name="groups",values = c(vec1="solid", vec2="dashed", vec3="dotted"))

Legend doesn't appear in the plot and there's no error message. What should I do to have legend?

vitor
  • 1,240
  • 2
  • 13
  • 27
  • [Here](http://stackoverflow.com/questions/20378276/legend-does-not-show-line-type-in-ggplot2-density-plot) is another answer. – Didzis Elferts Feb 17 '14 at 07:41
  • Don't understand why you guys are closing the question... I'm trying scale_linetype_manual like scale_colour_manual in other answers, but it doesn't work. – vitor Feb 17 '14 at 07:47
  • Did you put linetype="vec1", linetype="vec2" and linetype="vec3" inside the aes() of each geom_density()??? – Didzis Elferts Feb 17 '14 at 07:52
  • Put them inside the aes()? Just tried that, nothing happens. – vitor Feb 17 '14 at 07:56

1 Answers1

3

As explained already in previous questions (here and here) about the legends of ggplot2, if you need to make legend for the plot that uses several calls of geom_..., aesthetics (linetype) should be placed inside the aes() to add them to legend.

ggplot() + 
  geom_density(aes(x=x,linetype="vec1"), data=vec1) +
  geom_density(aes(x=x,linetype="vec2"), data=vec2) +
  geom_density(aes(x=x,linetype="vec3"), data=vec3) + 
  scale_linetype_manual(name="groups",
             values = c(vec1="solid", vec2="dashed", vec3="dotted"))

enter image description here

Community
  • 1
  • 1
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201