4.7 Making a Stacked Area Graph

4.7.1 Problem

You want to make a stacked area graph.

4.7.2 Solution

Use geom_area() andmap a factor to fill (Figure 4.20):

Stacked area graph

Figure 4.20: Stacked area graph

4.7.3 Discussion

The sort of data that is plotted with a stacked area chart is often provided in a wide format, but ggplot requires data to be in long format. To convert it, see Recipe 15.19.

In the example here, we used the uspopage data set:

This version of the chart (Figure 4.21) changes the palette to a range of blues and adds thin (size = .2) lines between each area. It also makes the filled areas semitransparent (alpha = .4), so that it is possible to see the grid lines through them:

Reversed legend order, lines, and a different palette

Figure 4.21: Reversed legend order, lines, and a different palette

Since each filled area is drawn with a polygon, the outline includes the left and right sides. This might be distracting or misleading. To get rid of it (Figure 4.22), first draw the stacked areas without an outline (by leaving colour as the default NA value), and then add a geom_line() on top:

No lines on the left and right of the graph

Figure 4.22: No lines on the left and right of the graph

4.7.4 See Also

See Recipe 15.19 for more on converting data from wide to long format.

See Chapter 12 for more on choosing colors.