3.4 Using Colors in a Bar Graph

3.4.1 Problem

You want to use different colors for the bars in your graph.

3.4.2 Solution

Map the appropriate variable to the fill aesthetic.

We’ll use the uspopchange data set for this example. It contains the percentage change in population for the US states from 2000 to 2010. We’ll take the top 10 fastest-growing states and graph their percentage change. We’ll also color the bars by region (Northeast, South, North Central, or West).

First, take the top 10 states:

Now we can make the graph, mapping Region to fill (Figure 3.9):

A variable mapped to fill

Figure 3.9: A variable mapped to fill

3.4.3 Discussion

The default colors aren’t the most appealing, so you may want to set them using scale_fill_brewer() or scale_fill_manual(). With this example, we’ll use the latter, and we’ll set the outline color of the bars to black, with colour="black" (Figure 3.10). Note that setting occurs outside of aes(), while mapping occurs within aes():

Graph with different colors, black outlines, and sorted by percentage change

Figure 3.10: Graph with different colors, black outlines, and sorted by percentage change

This example also uses the reorder() function to reorder the levels of the factor Abb based on the values of Change. In this particular case it makes sense to sort the bars by their height, instead of in alphabetical order.

3.4.4 See Also

For more about using reorder(), see Recipe 15.9.

For more information about using colors, see Chapter 12.