Udit Vashisht
Author: Udit Vashisht


How to fill area between the Line Plots? | Matplotlib Tutorial in Python | Chapter 5

  • 8 minutes read
  • 2028 Views
How to fill area between the  Line Plots? | Matplotlib Tutorial in Python | Chapter 5

    Table of Contents

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:
  • 'pre': The y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i].
  • 'post': The y value is continued constantly to the right from every x position, i.e. the interval [x[i], x[i+1]) has the value y[i].
  • 'mid': Steps occur half-way between the x positions.

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()

matplotlib_tutorial_filling_area__.png

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)

matplotlib_tutorial_filling_area_.png

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()

matplotlib_tutorial_filling_area_!_.png

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

matplotlib_tutorial_filling_area_!!_.png

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()

matplotlib_tutorial_filling_are!_.png

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.



Related Posts

Chapter 7- Numbers, Conversions and Operators
By Udit Vashisht

In the previous chapter, we learned about various datatypes. From this chapter onward, we will learn in detail about each data type.

Numbers in Python

This datatype stores the numeric values and is immutable. For the beginners, it is sufficient to understand that immutable objects are those which can ...

Read More
Python Realtime Plotting | Matplotlib Tutorial | Chapter 9
By Udit Vashisht

Python Realtime Plotting in Matplotlib

Python Realtime Plotting | Chapter 9

In this tutorial, we will learn to plot live data in python using matplotlib. In the beginning, we will be plotting realtime data from a local script and later on we will create a python live plot ...

Read More
Python Tutorial for Beginners
By Udit Vashisht

Python Tutorial for Beginners

Have you heard a lot about Python Language? Are you looking for free and reliable resource to learn Python? If Yes, your search for the Best Python Tutorial is over.

We are excited to bring an exhaustive Python tutorial for a complete beginner. Even ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas