Matplotlib Tutorial -5

Vivekawasthi
CodeX
Published in
3 min readNov 25, 2022

This tutorial will cover, Filling areas on line plots.

In the first tutorial, we covered line plots, here is the sample code for the same.

from matplotlib import pyplot as plt
import pandas as pd
plt.style.use('fivethirtyeight')
data = pd.read_csv('data_fill.csv')

Ages = data['Age']
PythonDev = data['Python']
AllDevs = data['All_Devs']

plt.plot(Ages,PythonDev, label='Python' )
plt.plot(Ages,AllDevs, label= 'AllDevs')

plt.legend()
plt.title('Median Salary')
plt.tight_layout()
plt.show()

fill_between() is used to fill the area between two horizontal curves. Two points (x, y1) and (x, y2) define the curves. this creates one or more polygons describing the filled areas. The ‘where’ parameter can be used to fill some areas selectively.

So suppose we want to fill the area between PythonDev and ages, we can add the below line.

plt.fill_between(Ages,PythonDev)

That fills the area between Ages and Python Dev, but it does not make more sense here, so if we put some threshold value and use the same in this plot, then it will make more sense.

Threshold_Value = 57287
plt.fill_between(Ages,PythonDev, Threshold_Value, alpha = 0.25)

Here, we have set the Threshold value as 57257 and alpha = 0.25 which is used to adjust the transparency of a graph plot. By default, alpha=1. If you want to make the graph plot more transparent, then you can make alpha less than 1, such as 0.5 or 0.25.

So, in the graph, we can clearly see, where the Python-Dev Salaries cross the threshold point, it filled the data above when the salary is lesser than the threshold point and below when it's above the threshold point.

Also, we can add a condition also, if we want to fill in where the salary is above the threshold value, we can put a condition for the same.

Also, I have used interpolate option, which is mostly used to impute missing values in the data frame or series while preprocessing data.

plt.fill_between(Ages,PythonDev, Threshold_Value,
where = (PythonDev > Threshold_Value )
,interpolate= True,alpha = 0.25)

So, it will fill the area when the salaries are above the threshold value, also we can put two conditions as well, one for greater than the threshold value and another for lesser than the threshold value.

plt.fill_between(Ages,PythonDev, Threshold_Value,
where = (PythonDev > Threshold_Value )
,interpolate= True,alpha = 0.25)
plt.fill_between(Ages,PythonDev, Threshold_Value,
where = (PythonDev < Threshold_Value )
,interpolate= True,alpha = 0.25)

So, we can easily analyze the data by filling the area.

In the next tutorial, we will cover Histograms using matplotlib.

--

--