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


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 <- data.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 <- data.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

4 Replies to “How to Create a Manual Legend in ggplot2 (With Examples)”

  1. How do you include a line type in in this? Usually when I include a line type, eg. “dashed”, I get a legend for that as “dashed” but that is not needed. So how do you add a line type that affects the legend with the color?

    1. Hi Kojo…In `ggplot2`, you can manually create a legend that combines color and line type without automatically generating a separate legend for the line type. To do this, you need to ensure that both the color and line type are mapped to the same aesthetic within a single call to `aes()`.

      Here’s how you can include a line type in your legend, combined with the color:

      ### Step-by-Step Guide

      1. **Map both color and line type to a single aesthetic**:
      – In `ggplot2`, you can map the color and line type to the same variable inside the `aes()` function. This ensures that the legend will show both the color and the line type together.

      2. **Use `scale_color_manual()` and `scale_linetype_manual()`**:
      – These functions allow you to manually specify the colors and line types that should appear in the legend.

      3. **Suppress unwanted legends**:
      – You can control which legends are displayed using the `guide = “none”` option inside `scale_*_manual()` functions or using `show.legend = FALSE` inside `geom_*()` functions.

      ### Example Code

      “`r
      library(ggplot2)

      # Sample data
      df <- data.frame( x = rep(1:10, 2), y = c(1:10, 2:11), group = rep(c("A", "B"), each = 10) ) # Plot with combined color and linetype in the legend ggplot(df, aes(x = x, y = y, color = group, linetype = group)) + geom_line(size = 1.2) + scale_color_manual(values = c("A" = "blue", "B" = "red")) + scale_linetype_manual(values = c("A" = "solid", "B" = "dashed")) + guides(color = guide_legend(override.aes = list(linetype = c("solid", "dashed")))) ``` ### Explanation - **Mapping**: Both `color` and `linetype` are mapped to the `group` variable in the `aes()` function. This ensures that the legend combines both aesthetics. - **Manual Scales**: - `scale_color_manual()`: Defines the colors for each group. - `scale_linetype_manual()`: Defines the line types for each group. - **Custom Legend**: - `guides(color = guide_legend(override.aes = list(linetype = c("solid", "dashed"))))`: This command customizes the legend so that the correct line types appear alongside the colors in the same legend entry. The `override.aes` argument in `guide_legend()` ensures that the legend shows the correct line types along with the colors. ### Suppressing Unwanted Legends If you want to include specific line types but avoid creating separate legends for them, make sure to avoid mapping `linetype` separately in other `aes()` calls, or you can suppress the unwanted legends: ```r geom_line(aes(...), show.legend = FALSE) ``` By following this approach, you can create a clear, concise legend that accurately reflects both the color and line type mappings in your plot.

Leave a Reply

Your email address will not be published. Required fields are marked *