Time for action – shading plot regions based on a condition

Imagine that you want to shade a region of a stock chart, where the closing price is below average, with a different color than when it is above the mean. The fill_between() function is the best choice for the job. We will, again, omit the steps of downloading historical data going back one year, extracting dates and close prices, and creating locators and date formatter.

  1. Create a matplotlib Figure object:
    fig = plt.figure()
  2. Add a subplot to the figure:
    ax = fig.add_subplot(111)
  3. Plot the closing price:
    ax.plot(dates, close)
  4. Shade the regions of the plot below the closing price using different colors depending on whether the values are below or above the average price:
    plt.fill_between(dates, ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.