How do you change the ggplot legend title?

I have created a plot using the following R code:

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

I want to change the legend title from “cond” to “NEW LEGEND TITLE”. I tried adding the following line to the code:

  • labs(colour=“NEW LEGEND TITLE”)

However, it did not work. What is the correct way to modify the legend title?the ggplot legend title?

To change the legend title in a ggplot2 plot, you can use the labs() function with the fill argument inside your ggplot() function.

Use labs() inside ggplot():

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

Yup, the above answer is quite effective but you can also use labs() after ggplot():

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

gg + labs(fill = “NEW LEGEND TITLE”)

This worked from me scale_fill_discrete() with name argument:

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

Of course, the above-given answers are not wrong; you can choose the method that best fits your workflow and coding style.