Home » How to Create a Manual Legend in ggplot2 (With Examples)

How to Create a Manual Legend in ggplot2 (With Examples)

by Tutor Aspire

Often you may want to add a manual legend to a plot in ggplot2 with custom colors, labels, title, etc.

Fortunately this is simple to do using the scale_color_manual() function and the following example shows how to do so.

Example: Create Manual Legend in ggplot2

The following code shows how to plot three fitted regression lines in a plot in ggplot2 with a custom manual legend:

library(ggplot2)

#create data frame
df frame(x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
                 y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))

#create plot with three fitted regression models
ggplot(df, aes(x, y)) +
  geom_point() +
  geom_smooth(se=FALSE, aes(color='Linear')) +
  geom_smooth(formula=y~poly(x, 2), se=FALSE, aes(color='Quadratic')) +
  geom_smooth(formula=y~poly(x, 3), se=FALSE, aes(color='Cubic')) +
  scale_color_manual(name='Regression Model',
                     breaks=c('Linear', 'Quadratic', 'Cubic'),
                     values=c('Cubic'='pink', 'Quadratic'='blue', 'Linear'='purple'))

Using the scale_color_manual() function, we were able to specify the following aspects of the legend:

  • name: The title of the legend
  • breaks: The labels in the legend
  • values: The colors in the legend

Note that we can also use the theme() function to modify the font size of the elements in the legend:

library(ggplot2)

#create data frame
df frame(x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
                 y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))

#create plot with three fitted regression models
ggplot(df, aes(x, y)) +
  geom_point() +
  geom_smooth(se=FALSE, aes(color='Linear')) +
  geom_smooth(formula=y~poly(x, 2), se=FALSE, aes(color='Quadratic')) +
  geom_smooth(formula=y~poly(x, 3), se=FALSE, aes(color='Cubic')) +
  scale_color_manual(name='Regression Model',
                     breaks=c('Linear', 'Quadratic', 'Cubic'),
                     values=c('Cubic'='pink', 'Quadratic'='blue', 'Linear'='purple'))+
 theme(legend.title=element_text(size=20),
       legend.text=element_text(size=14))

Notice that the font size of both the title and the labels in the legend were increased.

Additional Resources

The following tutorials explain how to perform other common operations in ggplot2:

How to Change Legend Position in ggplot2
How to Change Legend Size in ggplot2
How to Change Legend Title in ggplot2
How to Change Legend Labels in ggplot2

You may also like