7.1 Adding Text Annotations

7.1.1 Problem

You want to add a text annotation to a plot.

7.1.3 Discussion

The annotate() function can be used to add any type of geometric object. In this case, we used geom = "text".

Other text properties can be specified, as shown in Figure 7.2:

Modified text properties

Figure 7.2: Modified text properties

Be careful not to use geom_text() when you want to add individual text objects. While annotate(geom = "text") will add a single text object to the plot, geom_text() will create many text objects based on the data, as discussed in Recipe 5.11.

If you use geom_text(), the text will be heavily overplotted on the same location, with one copy per data point:

Overplotting one of the labels -- both should be 90\% transparent

Figure 7.3: Overplotting one of the labels – both should be 90% transparent

In Figure 7.3, each text label is 90% transparent, making it clear which one is overplotted. The overplotting can lead to output with aliased (jagged) edges when outputting to a bitmap.

If the axes are continuous, you can use the special values Inf and -Inf to place text annotations at the edge of the plotting area, as shown in Figure 7.4. You will also need to adjust the position of the text relative to the corner using hjust and vjust – if you leave them at their default values, the text will be centered on the edge. It may take a little experimentation with these values to get the text positioned to your liking:

Text positioned at the edge of the plotting area

Figure 7.4: Text positioned at the edge of the plotting area

7.1.4 See Also

See Recipe 5.11 for making a scatter plot with text.

For more on controlling the appearance of the text, see Recipe 9.2.