3.5 Coloring Negative and Positive Bars Differently

3.5.1 Problem

You want to use different colors for negative and positive-valued bars.

3.5.2 Solution

We’ll use a subset of the climate data and create a new column called pos, which indicates whether the value is positive or negative:

Once we have the data, we can make the graph and map pos to the fill color, as in Figure 3.11. Notice that we use position=“identity” with the bars. This will prevent a warning message about stacking not being well defined for negative numbers:

Different colors for positive and negative values

Figure 3.11: Different colors for positive and negative values

3.5.3 Discussion

There are a few problems with the first attempt. First, the colors are probably the reverse of what we want: usually, blue means cold and red means hot. Second, the legend is redundant and distracting.

We can change the colors with scale_fill_manual() and remove the legend with guide = FALSE, as shown in Figure 3.12. We’ll also add a thin black outline around each of the bars by setting colour and specifying size, which is the thickness of the outline (in millimeters):

Graph with customized colors and no legend

Figure 3.12: Graph with customized colors and no legend

3.5.4 See Also

To change the colors used, see Recipes Recipe 12.4 and Recipe 12.5.

To hide the legend, see Recipe 10.1.