How to Shade Regions Under the Curve in Python
In Python, you can use the fill_between
function from matplotlib to shade the desired regions under the curve.
The basic syntax for the fill_between
function is:
# impoat package
import matplotlib.pyplot as plt
plt.fill_between(x, y)
The fill_between
function requires values for the x and y coordinates to define the area for shading.
The following examples explain how to use the fill_between
function to shade the desired regions under the curve.
Example 1: Shade region under the single curve
Create a sample dataset for plotting the curve,
# impoat package
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
Now plot the curve and shade the area under the curve using matplotlib,
# impoat package
import matplotlib.pyplot as plt
# plot the curve
plt.plot(x, y, label='sin(x)')
# shade area under the single Curve
plt.fill_between(x, y, where=(y > 0))
plt.show()
In the above example, we used the fill_between
function to shade the region under the single curve. The region is shaded where the value of y-axis is > 0 (using the where
parameter).
Example 2: Shade region under two curves
You can also shade the region under the two curves in a single plot in Python.
Create a sample dataset for plotting the two curves,
# impoat package
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
Now plot the two curves and shade the area under two curves using matplotlib,
# impoat package
import matplotlib.pyplot as plt
# plot the curve
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
# shade are under two curves
plt.fill_between(x, y1, y2, where=(y1 > y2))
plt.legend()
plt.show()
In the above example, we used the fill_between
function to shade the region under two curves using the y1
and y2
coordinates. The region is shaded where the value of y1
is greater than y2
(using the where
parameter).
You can also use multiple conditions for y1
and y2
coordinates to shade the region under the curves,
# impoat package
import matplotlib.pyplot as plt
# plot the curve
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
# shade are under two curves
plt.fill_between(x, y1, where=(y1 > 0))
plt.fill_between(x, y2, where=(y2 > 0))
plt.legend()
plt.show()
In addition, you can also shade the specific region under the curves using the fill_between
function as explained in this article.