5.9 Adding Annotations with Model Coefficients

5.9.1 Problem

You want to add numerical information about a model to a plot.

5.9.2 Solution

To add simple text to a plot, simply add an annotation. In this example, we’ll create a linear model and use the predictvals() function defined in Recipe 5.7 to create a prediction line from the model. Then we’ll add an annotation:

This shows that the r^2 value is 0.4249. We’ll create a graph and manually add the text using annotate() (Figure 5.26):

Instead of using a plain text string, it’s also possible to enter formulas using R’s math expression syntax, by using parse = TRUE:

Plain text (left); Math expression (right)Plain text (left); Math expression (right)

Figure 5.26: Plain text (left); Math expression (right)

5.9.3 Discussion

Text geoms in ggplot do not take expression objects directly; instead, they take character strings that can be turned into expressions with R’s parse() function.

If you use a mathematical expression, the syntax must be correct for the expression to be a valid R expression object. You can test the validity by wrapping the object in the expression() function and seeing if it throws an error (make sure not to use quotes around the expression). In the example here, == is a valid construct in an expression to express equality, but = is not:

It’s possible to automatically extract values from the model object and build an expression using those values. In this example, we’ll create a string which when parsed, yields a valid expression:

Now that we have the expression string, we can add it to the plot. In this example we’ll put the text in the bottom-right corner, by setting x = Inf and y = -Inf and using horizontal and vertical adjustments so that the text all fits inside the plotting area (Figure 5.27):

Scatter plot with automatically generated expression

Figure 5.27: Scatter plot with automatically generated expression

5.9.4 See Also

The math expression syntax in R can be a bit tricky. See Recipe 7.2 for more information.