Creating line legends for geom_density in ggplot2 in R

with ggplot2, I do the following density graph:

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

A color legend (for each view value) appears as a window with a line passing through it, but the dense diagram is a line. Is there a way to make the legend displayed as soon as a colored line for each view record, and not a field with a line through it?

+8
r plot ggplot2
source share
2 answers

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

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

If you also need the entire area (all lines), you can combine geom_density() with show_guide=FALSE (to remove the legend) and stat_density() , than adding a legend with horizontal lines only.

 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

+14
source share

You can bypass a line of lines twice

 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: it’s a pity that you are not commenting on the clearly correct answer - the absence of problems with reputation :)

pps: I understand that the stream is quite old, but it helped me today, so it can someday help someone else ...

+1
source share

All Articles