10.5 Changing a Legend Title

10.5.1 Problem

You want to change the text of a legend title.

10.5.2 Solution

Use labs() and set the value of fill, colour, shape, or whatever aesthetic is appropriate for the legend (Figure 10.8):

With the legend title set to "Condition"With the legend title set to "Condition"

Figure 10.8: With the legend title set to “Condition”

10.5.3 Discussion

It’s also possible to set the title of the legend in the scale specification. Since legends and axes are both guides, this works the same way as setting the title of the x- or y-axis.

This would have the same effect as the previous code:

If there are multiple variables mapped to aesthetics with a legend (those other than x and y), you can set the title of each individually. In the example here we’ll use \n to add a line break in one of the titles (Figure 10.9):

Two legends with original titles (left); With new titles (right)Two legends with original titles (left); With new titles (right)

Figure 10.9: Two legends with original titles (left); With new titles (right)

If you have one variable mapped to two separate aesthetics, the default is to have a single legend that combines both. For example, if we map sex to both shape and weight, there will be just one legend (Figure 10.10, left):

To change the title (Figure 10.10, right), you need to set the name for both of them. If you change the name for just one, it will result in two separate legends (Figure 10.10, middle):

It is also possible to control the legend title with the guides() function. It’s a little more verbose, but it can be useful when you’re already using it to control other properties:

Default legend with a variable mapped to shape and colour (left); With shape renamed (middle); With both shape and colour renamed (right)Default legend with a variable mapped to shape and colour (left); With shape renamed (middle); With both shape and colour renamed (right)Default legend with a variable mapped to shape and colour (left); With shape renamed (middle); With both shape and colour renamed (right)Default legend with a variable mapped to shape and colour (left); With shape renamed (middle); With both shape and colour renamed (right)

Figure 10.10: Default legend with a variable mapped to shape and colour (left); With shape renamed (middle); With both shape and colour renamed (right)