making line legends for geom_density in ggplot2 in R

The show_guide function used in the answer by @liesb is deprecated under ggplot 3.0.0; it has been changed to show.legend:

ggplot(iris) + 
geom_density(aes(x=Sepal.Width, colour=Species),show.legend=FALSE) +
stat_density(aes(x=Sepal.Width, colour=Species),
             geom="line",position="identity", size = 0) + 
guides(colour = guide_legend(override.aes=list(size=1)))

ggplot(iris) + 
  stat_density(aes(x=Sepal.Width, colour=Species),
                  geom="line",position="identity")

Will do want you want.


You can get around plotting the lines twice by

ggplot(iris) + 
geom_density(aes(x=Sepal.Width, colour=Species),show_guide=FALSE) +
stat_density(aes(x=Sepal.Width, colour=Species),
             geom="line",position="identity", size = 0) + 
guides(colour = guide_legend(override.aes=list(size=1)))

ps: sorry for not commenting on the obviously correct answer -- lack of rep issues :)

pps: I realise the thread is quite old but it helped me today, so it might help someone else sometime...


One possibility is to use stat_density() with geom="line". Only in this case there will be only upper lines.

  ggplot(iris)+
    stat_density(aes(x=Sepal.Width, colour=Species),
                     geom="line",position="identity")

If you need also the whole area (all lines) then you can combine geom_density() with show_guide=FALSE (to remove legend) and stat_density() than will add legend just with horizontal lines.

ggplot(iris) + 
  geom_density(aes(x=Sepal.Width, colour=Species),show_guide=FALSE)+
  stat_density(aes(x=Sepal.Width, colour=Species),
                  geom="line",position="identity")

enter image description here

Tags:

Plot

R

Ggplot2