IcedCoffee IcedCoffee - 5 days ago 6
R Question

Adding a legend to a ggplot2 plot which contains multiple elements

This is a similar question to here however I could not get their solution to work for me. I want to add a legend to a ggplot2 plot, when using more than one independent data frame to generate the plot.

Here is an example based on the data sets available in R:

a=longley
b=iris
a$scaled=scale(a$Unemployed,center=TRUE,scale=TRUE)
b$scaled=scale(b$Sepal.Length,center=TRUE,scale=TRUE)
ggplot () +
geom_density(data=a,aes(x=scaled),fill="red",alpha=0.25) +
geom_density(data=b,aes(x=scaled),fill="blue",alpha=0.25) +
scale_colour_manual("",breaks=c("a","b"),values=c("red","blue"))


The plot produced looks like this:
Plot produced
ie. no legend.

How would I add a legend to this?

Answer

Very minor syntactic change required. Move the fill= part into the aes() statement in each geom.

a=longley
b=iris
a$scaled=scale(a$Unemployed,center=TRUE,scale=TRUE)
b$scaled=scale(b$Sepal.Length,center=TRUE,scale=TRUE)
ggplot () + 
    geom_density(data=a,aes(x=scaled,fill="red"),alpha=0.25) +
    geom_density(data=b,aes(x=scaled,fill="blue"),alpha=0.25)

This should work alone and will give you the default r color scheme. Or, if you really want to change the colors from the defaults, you can add the manual scale. However, since you want the scale to apply to the fill parameter, make sure to specify scale_fill_manual rather than scale_colour_manual.

ggplot () + 
    geom_density(data=a,aes(x=scaled,fill="red"),alpha=0.25) +
    geom_density(data=b,aes(x=scaled,fill="blue"),alpha=0.25) +
    scale_fill_manual("",breaks=c("a","b"),values=c("red","blue"))

If you wanted to change the colors of the lines you would do that with the color aesthetic and would then be able to use the scale_color_manual or scale_colour_manual (same thing) option.

ggplot() + 
    geom_density(data=a, aes(x=scaled, fill="red", color="yellow"), alpha=0.25) +
    geom_density(data=b, aes(x=scaled, fill="blue", color="green"), alpha=0.25) +
    scale_fill_manual(values=c("red","blue")) +
    scale_color_manual(values=c("yellow", "green"))