Legends (ggplot)

Legends are a key component of data visualization.  ggplot format controls are defined below.

Data

The diamonds data that ships with ggplot.

The Default Legend

The following example presents the default legend to be cusotmized.

Legend1

 

 

 

 

Click to enlarge

Removing the Legend

Legends are created for different aesthetics, such as fill, color/colour, linetype, shape, etc. Each aesthetic has a scale function than can be called to remove the legend:

Legend2

Removing the Legend Title

The logic is the same, but the syntax changes slightly to remove the legend key or title:

Legend3

Change the Legend Title and Text

The legend key is updated using the name argument and the labels are changed using the labels argument to the appropriate scale function.

Legend4

Of course, it also possible to modify the text in the original data.frame so the default chart legend is created with the preferred labels.

Formatting the Legend Key and Label Text

Sometimes legends are hard to read and require adjustment for improved emphasis or clarity.  For this purpose use the theme() function.

Legend5Legend6

Changing the Legend Position

The legend can be positioned outside of the plot box using the theme() function as follows.  Position options include “top”, “bottom”, “left” and “right”.  Legends can also be placed inside the plot box using x/y coordinates, where (0,0) is the lower left corner and (1,1) is the upper right corner.  This chart doesn’t lend itself to an internal, but the process is still shown.

Legend7Legend8

Changing Legend Item Order

Legend9

Managing Multiple Legends in a Layered Chart

ggplot supports the layering of multiple data objects and graph types.  Multilayered charts also present the challenge of managing multiple legends.  As before, legend control is tied to use of the appropriate scale function given previously declared aesthetics.  For example:

Legend10

Back | Next

Leave a Reply