How to fill area between the line plots in Matplotlib?
You can easily fill the area with any color between the lines or under a curve in Matplotlib Line Plots using plt.fill_between().
Parameters of matplotlib.pyplot.fill_between() or plt.fill_between()
The syntax for plt.fill_between() is :
matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)
And the parameters for fill_between() are :-
# | Parameter | Type | Description |
---|---|---|---|
1 | x | array (length N) | The x coordinates of the nodes defining the curves. |
2 | y1 | array (length N) or scalar | The y coordinates of the nodes defining the first curve. |
3 | y2 | array (length N) or scalar, optional, default: 0 | The y coordinates of the nodes defining the second curve. |
4 | where | array of bool (length N), optional, default: None | Define where to exclude some horizontal regions from being filled. The filled regions are defined by the coordinates x[where]. More precisely, fill between x[i] and x[i+1] if where[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values. |
5 | interpolate | bool, optional | This option is only relevant if where is used and the two curves are crossing each other. Semantically, where is often used for y1 > y2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the x array. Such a polygon cannot describe the above semantics close to the intersection. The x-sections containing the intersection are simply clipped. Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point. |
6 | step | {'pre', 'post', 'mid'}, optional | Define step if the filling should be a step function, i.e. constant in between x. The value determines where the step will occur:
|
Filling area under a simple line plot in Matplotlib
We will first create a simple Matplotlib Line Plot using plt.plot() and then fill the entire area under the curve using plt.fill_between().
# matplotlib_area_plots.py
import matplotlib.pyplot as plt
ages = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
total_population = [27877307, 24280683, 25258169, 25899454, 24592293, 21217467, 27958147, 20859088, 28882735, 19978972]
plt.plot(ages, total_population)
plt.xlabel("Age")
plt.ylabel("Total Population")
plt.title("Age-wise population of India")
plt.tight_layout()
plt.fill_between(ages, total_population)
plt.show()
Filling only a specific area under a curve in Matplotlib
You can also, fill upto a certain area/value by declaring y2 in plt.fill_between(). In the following example, we have set y2 as 25000000 and it will fill the area only between the total_population and the value of y2. Also, we have changed the opacity of the fill by passing the value of alpha to plt.fill_between().
plt.fill_between(ages, total_population, 25000000, alpha=0.30)
Here you can easily see, which age group has population above 25000000 and which has below it.
Filling area with different colour in Matplotlib-Conditional Filling of Area.
Now, we will fill the area between the lines/curve with different colors depending upon certain condition. To understand it better, we will again bring in the example of Cricket . Let us say, India is given a target of 89 runs in ten overs, meaning that the required run-rate is 8.9 runs per over. Now we will plot the run-rate of India at the end of each over as a line chart and then fill the area between the curve of the run-rate and required run-rate using plt.fill_between() and then we will set the color of the filled area depending upon the condition.
# matplotlib_area_plots.py
import matplotlib.pyplot as plt
overs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
run_rate = [6, 7.5, 8.3, 8, 9.2, 8.5, 9.4, 8.7, 8.8, 8.9]
plt.plot(overs, run_rate)
plt.xlabel("Overs")
plt.ylabel("Run Rate")
plt.title("Over-wise run rate of India")
plt.tight_layout()
plt.fill_between(overs, run_rate, 8.9, alpha=0.30)
plt.show()
So, above we have plotted the run-rate as a Matplotlib Line Plot and then filled the area between the curve and the required run-rate. Now to give it better visualisation, we need to color the area where the run-rate was above the required run-rate as green and the area where the run-rate was below the required run-rate as red. This will give us a clear picture of how the team has performed in every over. For this, we will be using numpy and changing the run-rate and required run-rate to arrays using np.array() so that we can check the condition using where.
# matplotlib_area_plots.py
import matplotlib.pyplot as plt
import numpy as np
overs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
run_rate = [6, 7.5, 8.3, 8, 9.2, 8.5, 9.4, 8.7, 8.8, 8.9]
required_run_rate = 8.9
z1 = np.array(run_rate)
z2 = np.array([required_run_rate] * 10)
plt.plot(overs, run_rate)
plt.xlabel("Overs")
plt.ylabel("Run Rate")
plt.title("Over-wise run rate of India")
plt.tight_layout()
plt.fill_between(overs, run_rate, required_run_rate,
where=(z1 < z2),
alpha=0.30, color='red', interpolate=True)
plt.fill_between(overs, run_rate, 8.9,
where=(z1 >= z2),
alpha=0.30, color='green', interpolate=True)
plt.show()
Setting labels/legends to filled area in Matplotlib
We can also set the labels in plt.fill_between() and then call plt.legend() to show the labels.
# matplotlib_area_plots.py
plt.fill_between(overs, run_rate, required_run_rate,
where=(z1 < z2),
alpha=0.30, color='red', interpolate=True, label='Below RRR')
plt.fill_between(overs, run_rate, 8.9,
where=(z1 >= z2),
alpha=0.30, color='green', interpolate=True, label='Above RRR')
plt.legend()
Filling area under the line curve in Matplotlib - Video
We are glad to inform you that we are coming up with the Video Tutorial Series of Matplotlib on Youtube. Check it out below.
Table of Contents of Matplotlib Tutorials in Python
Matplotlib Tutorial in Python | Chapter 1 | Introduction
Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts
Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3
Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4
Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5
Python Histograms | Matplotlib Tutorial in Python | Chapter 6
Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7
Plot Time Series in Python | Matplotlib Tutorial | Chapter 8
Python Realtime Plotting | Matplotlib Tutorial | Chapter 9
Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10
Python Candlestick Chart | Matplotlib Tutorial | Chapter 11
If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.
In case of any query, you can leave the comment below.
In the next chapter, we will learn about drawing Histograms in Matplotlib.
If you want to support our work. You can do it using Patreon.