12.7 Coloring a Shaded Region Based on Value

12.7.1 Problem

You want to set the color of a shaded region based on the y value.

12.7.3 Discussion

If you look closely at the figure, you’ll notice that there are some stray shaded areas near the zero line. This is because each of the two colored areas is a single polygon bounded by the data points, and the data points are not actually at zero. To solve this problem, we can interpolate the data to 1,000 points by using approx():

It would be more precise (and more complicated) to interpolate exactly where the line crosses zero, but approx() works fine for the purposes here.

Now we can plot the interpolated data (Figure 12.14). This time we’ll make a few adjustments – we’ll make the shaded regions partially transparent, change the colors, remove the legend, and remove the padding on the left and right sides:

Shaded regions with interpolated data

Figure 12.14: Shaded regions with interpolated data