8 Annotations

8.1 Titles

8.2 Labels

When constructing a data visualisation, it is often necessary to make annotations to the data displayed. Conceptually, an annotation supplies metadata for the plot: that is, it provides additional information about the data being displayed. From a practical standpoint, however, metadata is just another form of data. Because of this, the annotation tools in ggplot2 reuse the same geoms that are used to create other plots. However, to meet the specific needs that users often have when annotating plots, there are some helper functions in ggplot2 itself, and a number of other packages have extended ggplot2 in ways you may find helpful.

8.3 Text labels

Adding text to a plot is one of the most common forms of annotation. Most plots will not benefit from adding text to every single observation on the plot, but labelling outliers and other important points is very useful. However, text annotation can be tricky due to the way that R handles fonts. The ggplot2 package doesn’t have all the answers, but it does provide some tools to make your life a little easier. The main tool for labelling plots is geom_text(), which adds label text at the specified x and y positions. geom_text() has the most aesthetics of any geom, because there are so many ways to control the appearance of a text:

The ggplot2 package does allow you to map data values to the aesthetics used by geom_text(), but you should use restraint: it is hard to perceive the relationship between variables mapped to these aesthetics, and rarely useful to do so.

In addition to the various aesthetics, geom_text() has three parameters that you can specify. Unlike the aesthetics these only take single values, so they must be the same for all labels:

A variation on geom_text() is geom_label(): it draws a rounded rectangle behind the text. This makes it useful for adding labels to plots with busy backgrounds:

Labelling data well poses some challenges:

  • Text does not affect the limits of the plot. Unfortunately there’s no way to make this work since a label has an absolute size (e.g. 3 cm), regardless of the size of the plot. This means that the limits of a plot would need to be different depending on the size of the plot — there’s just no way to make that happen with ggplot2. Instead, you’ll need to tweak xlim() and ylim() based on your data and plot size.

  • If you want to label many points, it is difficult to avoid overlaps. check_overlap = TRUE is useful, but offers little control over which labels are removed. A popular technique for addressing this is to use the ggrepel package https://github.com/slowkow/ggrepel by Kamil Slowikowski. The package supplies geom_text_repel(), which optimizes the label positioning to avoid overlap. It works quite well so long as the number of labels is not excessive:

  • It can sometimes be difficult to ensure that text labels fit within the space that you want. The ggfittext package https://github.com/wilkox/ggfittext by Claus Wilke contains useful tools that can assist with this, including functions that allow you to place text labels inside the columns in a bar chart.

8.4 Building custom annotations

Labelling individual points with text is an important kind of annotation, but it is not the only useful technique. The ggplot2 package provides several other tools to annotate plots using the same geoms you would use to display data. For example you can use:

  • geom_text() and geom_label() to add text, as illustrated earlier.

  • geom_rect() to highlight interesting rectangular regions of the plot. geom_rect() has aesthetics xmin, xmax, ymin and ymax.

  • geom_line(), geom_path() and geom_segment() to add lines. All these geoms have an arrow parameter, which allows you to place an arrowhead on the line. Create arrowheads with arrow(), which has arguments angle, length, ends and type.

  • geom_vline(), geom_hline() and geom_abline() allow you to add reference lines (sometimes called rules), that span the full range of the plot.

Typically, you can either put annotations in the foreground (using alpha if needed so you can still see the data), or in the background. With the default background, a thick white line makes a useful reference: it’s easy to see but it doesn’t jump out at you. To illustrate how ggplot2 tools can be used to annotate plots we’ll start with a time series plotting US unemployment over time:

One useful way to annotate this plot is to use shading to indicate which president was in power at the time. To do this, we use geom_rect() to introduce shading, geom_vline() to introduce separators, geom_text() to add labels, and then use geom_point() to overlay the data on top of these background elements:

Notice that there is little new here: for the most part, annotating plots in ggplot2 is a straightforward manipulation of existing geoms. That said, there is one special thing to note in this code: the use of -Inf and Inf as positions. These refer to the top and bottom (or left and right) limits of the plot.

This technique can be applied in other ways too. For instance, you can use it to add a single annotation to a plot, but it’s a bit fiddly because you have to create a one row data frame:

This code works, and generates the desired plot, but it is very cumbersome. It would be annoying to have to do this every time you want to add a single annotation, so ggplot2 includes the annotate() helper function which creates the data frame for you:

The convenience of the annotate() function comes in handy in other situations. For example, a common form of annotation is to highlight a subset of points by drawing larger points in a different colour underneath the main data set. To highlight vehicles manufactured by Subaru you could use this to create the basic plot:

The problem with this is that the highlighted category would not be labelled. This is easily rectified using annotate()

This approach has the advantage of creating a label inside the plot region, but the drawback is that the label is distant from the points it picks out (otherwise the orange and black dot adjacent to the label might be confused for real data). An alternative approach is to use a different geom to do the work. geom_curve() and geom_segment() can be used to draw curves and lines connecting points with labels, and can be used in conjunction with annotate() as illustrated below:

8.5 Direct labelling

The Subaru plots above provide examples of “direct labelling”, in which the plot region itself contains the labels for groups of points instead of using a legend. This usually makes the plot easier to read because it puts the labels closer to the data. The broader ggplot2 ecosystem contains a variety of other tools to accomplish this in a more automated fashion. The directlabels package, by Toby Dylan Hocking, provides a number of tools to make this easier:

Directlabels provides a number of position methods. smart.grid is a reasonable place to start for scatterplots, but there are other methods that are more useful for frequency polygons and line plots. See the directlabels website, http://directlabels.r-forge.r-project.org, for other techniques.

Another take on this idea comes from the ggforce package by Thomas Lin Pederson https://github.com/thomasp85/ggforce. The ggforce package contains a lot of useful tools to extend ggplot2 functionality, including functions such as geom_mark_ellipse() that overlays a plot with circular “highlight” marks. For example:

A third approach to direct labelling is provided in the gghighlight package by Hiroaki Yutani https://github.com/yutannihilation/gghighlight. In many situations is useful for highlighting points or lines (or indeed a variety of different geoms) within a plot, particularly for longitudinal data:

8.6 Annotation across facets

When used well, annotations can be a powerful tool to help your reader make sense of your data. One example of this is when you want the reader to compare groups across facets. For example, in the plot below it is easy to see the relationship within each facet, but the subtle differences across facets do not pop out:

It is much easier to see these subtle differences if we add a reference line:

In this plot, each facet displays the data for one category agains the same regression line. This makes it easier to compare the facets to each other because there is shared reference line to assist the visual comparison.

A variation on this theme arises when you want each facet of a plot to display data from a single group, with the complete data set plotted unobtrusively in each panel to aid visual comparison. The gghighlight package is particularly useful in this context: