[r] How to change legend title in ggplot

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

This question is related to r plot ggplot2

The answer is


Adding this to the mix, for when you have changed the colors. This also worked for me in a qplot with two discrete variables:

p+ scale_fill_manual(values = Main_parties_color, name = "Main Parties")

I didn't dig in much into this but because you used fill=cond in ggplot(),

 + labs(color='NEW LEGEND TITLE') 

might not have worked. However it you replace color by fill, it works!

+ labs(fill='NEW LEGEND TITLE') 

This worked for me in ggplot2_2.1.0


Since you have two densitys I imagine you may be wanting to set your own colours with scale_fill_manual.

If so you can do:

df <- data.frame(x=1:10,group=c(rep("a",5),rep("b",5)))

legend_title <- "OMG My Title"

ggplot(df, aes(x=x, fill=group)) + geom_density(alpha=.3) +   
    scale_fill_manual(legend_title,values=c("orange","red"))

enter image description here


Since in your code you used ggplot(data, fill= cond) to create the histogram you need to add the legend title by also using "fill" in the label section i.e. +labs(fill="Title name"). If you were using a different type of plot where the code was ggplot(data, colour= cond), then you could use +labs(colour= "Title Name"). In summary, the lab argument has to match the aes argument.

I have used + guides(fill=guide_legend("my awesome title")) to change the legend title on geom_bar plots but it did not seem to work for geom_point.


ggplot(df) + labs(legend = '<legend_title>')


There's another very simple answer which can work for some simple graphs.

Just add a call to guide_legend() into your graph.

ggplot(...) + ... + guide_legend(title="my awesome title")

As shown in the very nice ggplot docs.

If that doesn't work, you can more precisely set your guide parameters with a call to guides:

ggplot(...) + ... + guides(fill=guide_legend("my awesome title"))

You can also vary the shape/color/size by specifying these parameters for your call to guides as well.


I noticed there are two ways to change/specify legend.title for ggboxplot():

library(ggpubr)

bxp.defaultLegend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                               color = "dose", palette = "jco")

# Solution 1, setup legend.title directly in ggboxplot()
bxp.legend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco", legend.title="Dose (mg)")

# Solution 2: Change legend title and appearnace in ggboxplot() using labs() and theme() option:
plot1 <-  bxp.defaultLegend + labs(color = "Dose (mg)") +
  theme(legend.title = element_text(color = "blue", size = 10), legend.text = element_text(color = "red"))

ggarrange(list(bxp.legend, bxp.defaultLegend, plot1), nrow = 1, ncol = 3,  common.legend = TRUE)

The code is modified based on the example from GitHub.


Just to add to the list (the other options here didn't work for me), you can also use the function update_labels for ggplot:

p <- ggplot(df, aes(x=rating, fill=cond)) + 
           geom_density(alpha=.3) + 
           xlab("NEW RATING TITLE") + 
           ylab("NEW DENSITY TITLE")
update_labels(p, list(colour="MY NEW LEGEND TITLE")

This will also allow you to change x- and y-axis labels, with separate lines:

update_labels(p, list(x="NEW X LABEL",y="NEW Y LABEL")

Many people spend a lot of time changing labels, legend labels, titles and the names of the axis because they don't know it is possible to load tables in R that contains spaces " ". You can however do this to save time or reduce the size of your code, by specifying the separators when you load a table that is for example delimited with tabs (or any other separator than default or a single space):

read.table(sep = '\t')

or by using the default loading parameters of the csv format:

read.csv()

This means you can directly keep the name "NEW LEGEND TITLE" as a column name (header) in your original data file to avoid specifying a new legend title in every plot.


None of the above code worked for me.

Here's what I found and it worked.

labs(color = "sale year")

You can also give a space between the title and the display by adding \n at the end.

labs(color = 'sale year\n")


The way i am going to tell you, will allow you to change the labels of legend, axis, title etc with a single formula and you don't need to use memorise multiple formulas. This will not affect the font style or the design of the labels/ text of titles and axis.

I am giving the complete answer of the question below.

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

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

 # to change the cond to a different label
 k$labels$fill="New Legend Title"

 # to change the axis titles
 k$labels$y="Y Axis"
 k$labels$x="X Axis"
 k

I have stored the ggplot output in a variable "k". You can name it anything you like. Later I have used

k$labels$fill ="New Legend Title"

to change the legend. "fill" is used for those labels which shows different colours. If you have labels that shows sizes like 1 point represent 100, other point 200 etc then you can use this code like this-

k$labels$size ="Size of points"

and it will change that label title.


I am using a facet_wrap in my ggplot and none of the suggested solutions worked for me except ArnaudA's solution:

qplot(…) + guides(color=guide_legend(title="sale year")) 

Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to plot

Fine control over the font size in Seaborn plots for academic papers Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python Modify the legend of pandas bar plot Format y axis as percent Simple line plots using seaborn Plot bar graph from Pandas DataFrame Plotting multiple lines, in different colors, with pandas dataframe Plotting in a non-blocking way with Matplotlib What does the error "arguments imply differing number of rows: x, y" mean? matplotlib get ylim values

Examples related to ggplot2

Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph Saving a high resolution image in R Change bar plot colour in geom_bar with ggplot2 in r Remove legend ggplot 2.2 Remove all of x axis labels in ggplot Changing fonts in ggplot2 Explain ggplot2 warning: "Removed k rows containing missing values" Error: package or namespace load failed for ggplot2 and for data.table In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric