user248237
user248237

Reputation:

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?

Upvotes: 31

Views: 18083

Answers (5)

Nick O'Grady
Nick O'Grady

Reputation: 21

If you want to fill the boxes in the legend, add fill in geom_density, but use alpha=0 and override the legend to alpha=1. Like this:

ggplot(iris) + 
  geom_density(aes(x=Sepal.Width, colour=Species, fill = Species), alpha = 0) +
  guides(colour = guide_legend(override.aes = list(alpha = 1)))

Upvotes: 2

Frish Vanmol
Frish Vanmol

Reputation: 364

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

Will do want you want.

Upvotes: 7

Martin Monkman
Martin Monkman

Reputation: 121

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)))

Upvotes: 10

liesb
liesb

Reputation: 53

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...

Upvotes: 1

Didzis Elferts
Didzis Elferts

Reputation: 98579

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

Upvotes: 35

Related Questions