Introduction
In this lab, we will learn how to shade regions in a Matplotlib plot using the fill_between function. This is useful for highlighting specific areas of the plot, such as regions where a certain condition is met.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Import Necessary Libraries
We will start by importing the necessary libraries for this lab, which are numpy and matplotlib.pyplot.
import numpy as np
import matplotlib.pyplot as plt
Create Data
We will create some data to use for our plot. In this example, we will create a sine wave.
t = np.arange(0.0, 2, 0.01)
s = np.sin(2*np.pi*t)
Create the Plot
Now we will create the plot using matplotlib.pyplot. We will plot the sine wave and add a horizontal line at y=0.
fig, ax = plt.subplots()
ax.plot(t, s, color='black')
ax.axhline(0, color='black')
Shade the Regions
We will use fill_between to shade the regions above and below the horizontal line where the sine wave is positive and negative, respectively.
ax.fill_between(t, 1, where=s > 0, facecolor='green', alpha=.5)
ax.fill_between(t, -1, where=s < 0, facecolor='red', alpha=.5)
Show the Plot
Finally, we will show the plot using plt.show().
plt.show()
Summary
In this lab, we learned how to shade regions in a Matplotlib plot using the fill_between function. This is a useful tool for highlighting specific areas of the plot. We hope you found this lab helpful!