Time for action – shading plot regions based on a condition
Imagine that you want to shade the 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 1
year, extracting dates and close prices, and creating locators and date formatter.
Create a Matplotlib figure object.
fig = plt.figure()
Add a subplot to the figure.
ax = fig.add_subplot(111)
Plot the closing price.
ax.plot(dates, close)
Shade the regions of the plot below the closing price using different colors depending whether the values are below or above the average price.
plt.fill_between(dates, close.min(), close, where=close>close.mean(), facecolor="green", alpha=0.4) plt.fill_between(dates, close.min(), close, where=close<close.mean(), facecolor="red", alpha=0.4)
Now we can finish the plot by setting locators and formatting the x-axis values...