7.8 Adding Annotations to Individual Facets

7.8.1 Problem

You want to add annotations to each facet in a plot.

7.8.3 Discussion

This method can be used to display information about the data in each facet, as shown in Figure 7.18. For example, in each facet we can show linear regression lines, the formula for each line, and the r2 value. To do this, we’ll write a function that takes a data frame and returns another data frame containing a string for a regression equation, and a string for the r2 value. Then we’ll use dplyr’s do() function to apply that function to each group of the data:

Annotations in each facet with information about the data

Figure 7.18: Annotations in each facet with information about the data

We needed to write our own function here because generating the linear model and extracting the coefficients requires operating on each subset data frame directly. If you just want to display the r2 values, it’s possible to do something simpler, by using the group_by() and with the summarise() function and then passing additional arguments for summarise():

Text geoms aren’t the only kind that can be added individually for each facet. Any geom can be used, as long as the input data is structured correctly.

7.8.4 See Also

See Recipe 7.2 for more about using math expressions in plots.

If you want to make prediction lines from your own model objects, instead of having ggplot2 do it for you with stat_smooth(), see Recipe 5.8.