Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having all layers in the legend with ggplot

Tags:

r

legend

ggplot2

how could I make a legend representing all the curves that are plotted in my graph ? Presently, an automatic legend is generated for the first layer (based on the "colour" aesthetic), but the other layer (the black curve representing the density of "price" variable across all observations) in not contained in this legend.

I conceive that my question comes certainly from an incomplete understanding of the concepts behing ggplot package.

ggplot(diamonds) + 
  geom_density(aes(x = price, y = ..density.., colour = cut)) +
  geom_density(aes(x = price,y = ..density..))

enter image description here

like image 248
fstevens Avatar asked Nov 15 '12 09:11

fstevens


1 Answers

The principle in ggplot2 is that each aesthetic gets mapped to a scale. So, if you want to include a layer in the colour scale, you need to map that layer to colour.

Like this:

ggplot(diamonds, aes(x=price)) + 
  geom_density(aes(colour = cut)) +
  geom_density(aes(colour="Overall"), size=1.5)

enter image description here


Note: You can take additional control over the colours by specifying a manual colour scale:

ggplot(diamonds, aes(x=price)) + 
  geom_density(aes(colour = cut)) +
  geom_density(aes(colour="Overall"), size=1.5) +
  scale_colour_manual(
    limits=c("Overall", levels(diamonds$cut)),
    values=c("black", 2:6)
    )

enter image description here

like image 76
Andrie Avatar answered Sep 25 '22 21:09

Andrie