Adding text descriptions to graphs

Sometimes, we might wish to add descriptions to a graph, say if we are producing a PDF for a presentation or as a handout with notes. In this recipe, we will learn how to add text descriptions in the margins of a graph, instead of having to add them separately in another program.

We are only using the base graphics functions for this recipe. So, just open up the R prompt and type in the following code. You might wish to save the code as an R script for later use.

Let's plot a random normal distribution and add a little bit of description after the graph:

How to do it...

In the example, we set the bottom margin of the plot to a high value and used the mtext() function to add a small description below the graph.

We created an expression called desc with the expression() function we saw in the previous recipe and used mtext() to place it in the fourth line of the bottom margin. To make the text top-left aligned, we set padj to 1 and adj to 0. We used mtext() again to place the other half of the description on the seventh line of the margin. We had to split the description into two halves and use mtext() twice because we couldn't automatically line-wrap an expression. We will soon see another example with a text-only description, where we can wrap it in just one mtext() function call.

Let's look at another example, where we add the description before the graph but just below the title. This time the description will just be plain text and will not contain any expressions. We will use the dailysales.csv example dataset and make a line graph of daily sales data:

There's more

In the example, we set the margins such that the top margin is 12 lines wide. We created a string called desc with the description for the graph. We then used mtext() to place the string in the third line of the margin. We couldn't simply pass desc to mtext() because it wouldn't fit within the width of the plot area and would get chopped off after the first sentence. So, we used the strwrap() function to wrap the string with a width of 80 characters. We used the paste() function to join the split strings created by strwrap(), with line breaks added by setting the collapse argument to "\n". Finally, we used the title() function to add a graph title on top.