Search code examples
rplotggplot2

making line legends for geom_density in ggplot2 in R


with ggplot2, I make the following density plot:

ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species))

The colour legend (for each Species value) appears as a box with a line through it, but the density plotted is a line. Is there a way to make the legend appear as just a colored line for each entry of Species, rather than a box with a line through it?


Solution

  • 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