How to change legend title in ggplot

neversaint picture neversaint · Jan 31, 2013 · Viewed 578k times · Source

I have the following plot like below. It was created with this command:

library(ggplot2)

df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)), 
                 rating = c(rnorm(200), rnorm(200, mean=.8)))

ggplot(df, aes(x=rating, fill=cond)) + 
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")

Now next thing I want to do is to modify the legend title from cond into NEW LEGEND TITLE.

So what I did is to just add the following line add the end of the above code:

+labs(colour="NEW LEGEND TITLE")

But it doesn't work. What's the right way to do it?

enter image description here

Answer

Arun picture Arun · Jan 31, 2013

This should work:

p <- ggplot(df, aes(x=rating, fill=cond)) + 
           geom_density(alpha=.3) + 
           xlab("NEW RATING TITLE") + 
           ylab("NEW DENSITY TITLE")
p <- p + guides(fill=guide_legend(title="New Legend Title"))

(or alternatively)

p + scale_fill_discrete(name = "New Legend Title")