Chapter 5 Text Annotations

5.1 Introduction

In this chapter, we will learn to add text to the plots.

  • add custom text
  • modify color
  • modify size
  • modify fontface
  • modify angle

5.2 Annotate

We will use the annotate() function to add custom text to the plots. You can use the annotate() function to add rectangles/segments/pointrange as well but our focus will be on adding text. Let us start with a simple scatter plot.

annotate() takes the following arguments:

  • geom : specify text
  • x : x axis location
  • y : y axis location
  • label : custom text
  • color : color of text
  • size : size of text
  • fontface : fontface of text
  • angle : angle of text

5.2.1 Add Text

Let us begin by adding text to a scatter plot. We will use the mtcars data set and continue to examine the relationship between displacement and miles per gallon. To add the text, we have to indicate that we are using annotate() for adding text, and we do this by ensuring that the first input is the word 'text'. Now, ggplot2 knows that it should add a text to the plot but it still needs other information such as:

  • where should the text appear on the plot i.e. location of the text
  • and the text itself

We will provide the location by specifying points on the X and Y axis which are also the second and third inputs to annotate() and the final input is the text itself, which in our example is 'Sample Text'.

5.2.2 Color

Now that we know how to add text, let us look at modifying the appearance of the text. To change the color, use the color argument. In the below example, we modify the color to 'red'.

5.2.3 Size

The size argument can be used to modify the size of the text.

5.2.4 Font

To choose a font of your liking, use the font argument and supply it a valid value.

5.2.5 Angle

The angle of the text can also be modified using the angle argument. In the below example, we modify the angle of the text to 25.