Matplotlib fill_between – Complete Guide

In this Python Matplotlib tutorial, we will discuss Matplotlib fill_between in python. Here we will cover different examples related to the fill_between using matplotlib. And we will also cover the following topics:

  • Matplotlib fill_between
  • Matplotlib fill_between example
  • Matplotlib fill_between color
  • Matplotlib fill_between hatch
  • Matplotlib fill_between step
  • Matplotlib fill_between hatch color
  • Matplotlib fill between facecolor
  • Matplotlib fill_between hatch density
  • Matplotlib fill_between where
  • Matplotlib fill between three lines
  • Matplotlib fill between two curves
  • Matplotlib fill between scatter
  • Matplotlib fill between dashed
  • Matplotlib fill between circle
  • Matplotlib fill between two lines
  • Matplotlib fill_between alpha
  • Matplotlib fill_between log scale
  • Matplotlib fill_between legend
  • Matplotlib fill_between line color
  • Matplotlib fill_between line width
  • Matplotlib fill_between no edge
  • Matplotlib fill_between edge
  • Matplotlib fill_between edgecolor
  • Matplotlib fill_between datetime
  • Matplotlib fill between range
  • Matplotlib fill between error bars
  • Matplotlib fill between two vertical lines
  • Matplotlib fill between two horizontal lines
  • Matplotlib fill between on top
  • Matplotlib fill_between pandas
  • Matplotlib fill between 0
  • Matplotlib fill between points
  • Matplotlib fill between different colors
  • Matplotlib fill between style
  • Matplotlib label for fill_between
  • Matplotlib fill_between interpolate
  • Matplotlib fill_between confidence interval
  • Matplotlib fill between standard deviation
  • Matplotlib fill between x axis
  • Matplotlib fill between polygon
  • Matplotlib fill_between polar
  • Matplotlib fill_between animation
Table of Contents show

Matplotlib fill_between

In this section, we’ll learn about the fill_between function in the pyplot module of matplotlib in Python.

  • The fill_between function is used to fill the space or region between two horizontal curves or lines. The points (x, y1) and (x, y2) are used to define the curves, which form one or more polygons that describe the filled region.
  • By using the “where” parameter you may ignore some horizontal sections from filling.
  • Edges connect the provided places directly by default. However, the “step” argument can be used if the filling should be a step function (constant between x).

The syntax for the fill_between function is:

matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, 
                              interpolate=False, 
                              step=False, *, 
                              data=None, **kwargs) 

The parameters for the fill_between function are:

ParameterValueDescription
xarray of length NThe node’s of x coordinates, are used to define the curves.
y1array of length N or scalarThe y coordinates of the nodes, used for defining the first curve.
y2array of length N or scalar
By default: 0
The y coordinates of the nodes, used for defining the second curve
wherearray of bool of length NIt is used when there is a need to exclude some horizontal region from being filled. Here 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: This definition means that an isolated True value between two False values in where will not result in filling.
Due to adjacent False values, both sides of the True position remain unfilled.
interpolatebool
By default: False
This option is only used if the where parameter is used and the two curves intersect. where is used for y1>y2 or similar.
The nodes of the polygon used to define the filled region are only inserted at the x array position by default. The above semantics seem unable to describe such polygons.
The intersections in the x-sections are simply clipped. When you set interpolate to True, the filled region will be extended up to the actual intersection point.
step{ ‘pre’, ‘post’, ‘mind’ }This parameter is used, 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.
* ‘post’ : The y value is continued constantly to the right from every x position.
* ‘mid’ : If the step occurs halfway between the x position.
dataindexable objectThis parameter also accepts a string, which is interpreted as data[s] (unless exception raises).
** kwargsAll other arguments, that are used to control the Polygon Properties.
Parameters

Returns:

From the PolyCollection, it returns a plotted polygon.

Also, check: Draw vertical line matplotlib

Matplotlib fill_between example

Here we’ll learn a simple example of the fill_between() function. We’ll create a simple line plot using the plot() method of matplotlib and after that, we fill the entire region under the curve using the fill_between function.

Source Code:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates

x = [0, 1, 2, 3, 4, 5]
y = [1.5, 3, 5.3, 6, 10, 2]

# Plot

plt.plot(x, y, '-o', color='red')

# fill_between

plt.fill_between(x, y)

# Add title

plt.suptitle('Simple fill_between Example', fontweight='bold')

# Display

plt.show()

Explanation of source code:

  • To import matplotlib library, we use import matplotlib.pyplot.
  • After this, we define x and y data coordinates, that define the curves.
  • To create a line plot, we use plt.plot() method.
  • To fill the entire area under the curves, we use plt.fill_between() method.
  • Then we add a suptitle, by using plt.suptitle() method.
  • To visualize the plot on the user’s screen, we use plt.show() method.

Output:

matplotlib fill_between example
fill_between

Read: Matplotlib invert y axis

Matplotlib fill_between color

Here we’ll learn how to fill the area of a figure with the color of your choice in matplotlib using Python. For this, we have to pass a color argument to the fiil_between function and set the color of your choice.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, color=None)

Source Code:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates

x = [0, 1, 2, 3, 4, 5]
y = [1.5, 3.6, 4.6, 5, 8, 2.5]

# Plot

plt.plot(x, y, '-o')

# fill_between

plt.fill_between(x, y, color='yellow')

# Add title

plt.suptitle('fill_between color', fontweight='bold')

# Display

plt.show()

Explanation of Source Code:

  • Firstly, we import matplotlib.pyplot library.
  • After this, we define data coordinates that define the curves.
  • To plot a line chart, we use plt.plot() method of matplotlib.
  • Then to fill the area under the curve with the color of your choice, we pass color as an argument to fill_between function.
  • By using the plt.suptitle() method, we define the title of the plot.
  • To visualize the chart on the user’s screen, we use plt.show() method.

Generated Chart:

matplotlib fill_between color
fill_between(color=’yellow’)

Read: Put legend outside plot matplotlib

Matplotlib fill_between hatch

In the section, we’ll learn about fill_between hatch. We have already studied fill_between in the above topics. Now it’s time to learn something about the hatch.

In most cases, we use colors to fill the background while creating plots, but using patterns to fill the background is a good alternative in the following cases:

  • When plots include black and white background.
  • When we want to reduce the number of colors.

To fill the plots with a pattern, we assign a new parameter hatch with values as a string. Some of the string values are: / , \\ , | , , + , x , o, . , *

The syntax is given below:

matplotlib.pyplot.fill_between(x, y, hatch=None)

Source Code:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates

x = [2, 6]
y = [2, 6]

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y, color= 'none', hatch="o",   
                 edgecolor="g")

# Display

plt.show()

Explanation of Source Code:

  • Here we fill the entire region below the curves with a pattern bypassing hatch parameter to the fill_between() method of matplotlib. We also assign none to the color parameter, so that background remains plain.
  • We assign green to the edgecolor parameter.

Output:

matplotlib fill_between hatch
fill_between(hatch=’o’)

Read: Matplotlib save as pdf

Matplotlib fill_between step

Here we’ll learn about the step parameter. This parameter is used, if the filling should be constant in between x.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, step=None)

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(20, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Plot

plt.plot(x, y1)
plt.plot(x, y2)

# fill_between

plt.fill_between(x, y1, step="pre", alpha=0.2)
plt.fill_between(x, y2, step="pre", alpha=5.5)

# Display

plt.show()

Explanation:

  • Here we import the matplotlib.pyplot and numpy library.
  • After this, we define data coordinates using numpy.
  • To plot the curves (x, y1) and (x, y2), we use the plt.plot() method of matplotlib.
  • To fill the area below the curves, we use the fill_between() method and pass x and y with step parameter and assign them “pre” as a value. The value determines where the step will occur.
  • To display the figure, use the show() method.

Output:

matplotlib fill_between step
fill_between(step=’pre’)

Read: Matplotlib title font size

Matplotlib fill_between hatch color

Here we’ll learn what will happen to hatch when we specify the color by using color as a parameter.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, hatch=None, color=None)

Source Code:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates

x = [1, 3]
y = [1, 3]

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y, hatch='+', color='red')

# Display

plt.show()

Explanation:

  • In the above example, we define data coordinates x and y and plot the curve by using the plt.plot() method of matplotlib.
  • After this, we use the fill_between() function with x, y, hatch, and color as a parameter and set their values as x-coordinates, y-coordinates, +, and red respectively.

Output:

matplotlib fill_between hatch color
hatch with color

Observation:

Hatches are invisible in the output when color is specified.

Matplotlib fill between facecolor

Here we’ll see an example where we use the fill_between() function with facecolor argument.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, hatch=None, facecolor=None)

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(20, 10, 100)
y = np.sin(x)

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y, hatch='O', facecolor='yellow')

# Display


plt.show()

Explanation of Source Code:

  • In the above example, we define data coordinates using the linespace() and the sin() methods of numpy.
  • To plot the curve, we use the plt.plot() method of matplotlib.
  • Then we use the fill_between() method with x, y, hatch, and facecolor arguments.
matplotlib fill between facecolor
fill_between(facecolor=’yellow’)

Conclusion:

Hatches are visible in the output when facecolor argument is used but absent when we use color argument.

Read: Matplotlib default figure size

Matplotlib fill_between hatch density

Here we’ll learn how we can increase the density of hatch patterns. To obtain the denser pattern, we have to assign a pattern string in even numbers to the hatch parameter.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, hatch=string pattern in even number)

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(20, 10, 100)
y = np.cos(x)

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y, hatch='\\\\', facecolor='cyan')

                            # OR

plt.fill_between(x, y, hatch='\\\\\\\\', facecolor='cyan')

# Display

plt.show()

Explanation:

  • Here we use the fill_between() method with facecolor and hatch argument and set their value to cyan, backslash respectively.
  • In the first case, we pass 4 backslashes and in the second case, we pass 8 backslashes.

Output:

matplotlib fill_between hatch density
With 4 slashes
matplotlib fill_between with hatch densit
With 8 slashes

Conclusion:

We concluded that we can increase the density of the hatch by increasing the number of patterns.

Read: Matplotlib savefig blank image

Matplotlib fill_between where

Here we’ll learn about the where parameter of the fill_between() method. This parameter is used when there is a need to exclude some horizontal region from being filled.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, where= condition applied )

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(0,10,25)
y = np.sin(x)

# Plot curves

plt.plot(x,y, color='k')

# fill_between

plt.fill_between(x, y, where = (x > 5) & (y <= 4),
                 color = 'orange')
# Display

plt.show()

Explanation:

  • In the above example, we firstly import important libraries such as matplotlib.pyplot, and numpy.
  • After this, we define data coordinates by using numpy functions.
  • To plot the curves, use the plot() method of pyplot.
  • Next, we use the fill_between() method with where parameter which specifies the condition on the area to fill. Here we specify the condition to fill the area which lies between x>5 and y<=4.
matplotlib fill_between where
fill_between(where)

Read: Matplotlib save as png

Matplotlib fill between three lines

In this section, we’ll see the use of fill_between while filling the area between three lines.

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data


x = np.linspace(0,3,100)
y1 = X**4 + 20
y2 = np.exp(X) + 5
y3 = np.sin(X)

# Plot

plt.plot(x , y1, color='k')
plt.plot(x, y2, color='k')
plt.plot(x, y3, color='k')

# fill_between


plt.fill_between(x, y1, y2, color='red')
plt.fill_between(x, y2, y3, color='yellow')

# Display

plt.show()

Explanation:

  • In the above example, we create three lines plot, and by using the fill_between() method we fill the area between lines with different colors.
  • Firstly we fill the area, between y1 and y2 by using the fill_between() method and we set the color red by using the parameter color.
  • Then we fill the area, between y2 and y3 by using the fill_between() method and we set its color to yellow by using a color parameter.
matplotlib fill between three lines
fill between three lines

Read: Add text to plot matplotlib in Python

Matplotlib fill between two curves

Here we see an example where we fill the area between two curves by using the fill_between() method.

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0.01,20,0.1)
y1 = 5.0 / np.exp(x)
y2 = np.log(x)

# Plot

plt.plot(x, y1, color='k')
plt.plot(x, y2, color='k')

# fill_between

plt.fill_between(x, y1, y2, color='red')

# Display


plt.show()
  • Here we create curves by using arange(), exp(), log() methods of numpy.
  • Then we fill the area between curves by using the fill_between() method.
matplotlib fill between two curves
fill between curves

Read: Matplotlib bar chart labels

Matplotlib fill between scatter

Here we’ll see an example where we fill the region between scatter plots using the fill_between method of the matplotlib library.

Source Code:

# Import library

import matplotlib.pyplot as plt
import numpy as np
 
# Define Data

x = np.arange(0, 20, 0.2)
y1 = np.sin(x)
y2 = np.cos(x)
 
# Scatter Plot

plt.scatter(x, y1)
plt.scatter(x, y2)

# fill_between

plt.fill_between(x, y1, where = (x <=3 ) & (y1 <= 4))

# Display

plt.show()

Here we create a scatter plot by using plt.scatter() method and then we use the fill_between() method to fill the region where x<= 3 and y1<=4.

matplotlib fill between scatter
fill between scatter

Read: Matplotlib set_yticklabels – Helpful Guide

Matplotlib fill between dashed

Here we’ll see an example of a dashed line plot.

Source Code:

# Import library

import matplotlib.pyplot as plt
import numpy as np

# Define Data coordinates

x = np.arange(2, 8, 0.2)
y = x*2

# Plot

plt.plot(x,y,'k--', linewidth = 8)

# fill_between

plt.fill_between(x, y, np.min(x), color='m')

# Display

plt.show()

Explanation:

  • In the above example, we import matplotlib.pypplot and numpy library.
  • Next , we define data coordinates by using arange() method of numpy.
  • Then we plot a dashed line between x and y by using plot() method with linestyle parameter.
  • To fill the area between two horizontal curves, we use the fill_between() method and we also specify color of region to magenta.
matplotlib fill between dashed
fill between dashed

Read: Matplotlib tight_layout – Helpful tutorial

Matplotlib fill between circle

Here we’ll see an example where we fill color between circles.

Source Code:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create subplots

figure, axes = plt.subplots( 1 )

# Define Data

data = np.linspace( 0 , 2 * np.pi , 150 )
radius = 0.6
a = radius * np.cos( data )
b = radius * np.sin( data )
 
# Plot

axes.plot( a, b )

# fill between

plt.fill_between(a, b, facecolor='yellow')

# Display

plt.show()
  • Here we draw a circle by using the parametric equation of a circle.
  • After this, we fill the region between the circle by using the fill_between() method.
matplotlib fill between circle
fill between circle

Read: Python Matplotlib tick_params

Matplotlib fill between two lines

Here we’ll see an example where we will shade the region between two lines.

Source Code:

# Import Library

import matplotlib.pyplot as plt

# Define Data coordinates

x =  [0, 1, 2, 3, 4, 5]
y1 = [30, 60, 90, 120, 150, 180]
y2 = [20, 40, 60, 80, 100, 120]

# Shade the region

plt.fill_between(x, y1, y2, facecolor='pink')

# Show the plot


plt.show()

Here we use the fill_between() method to shade the region between two lines. We also pass the facecolor parameter and set its value to pink.

matplotlib fill between two lines
fill between two lines

Read: Matplotlib x-axis label

Matplotlib fill_between alpha

Here we’ll learn to use the alpha parameter in the fill_between() method. By using an alpha attribute, we can regulate the transparency of a graph plot, Default, alpha=1.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, facecolor=None, alpha=1)

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(2, 8, 0.2)
y = np.sin(30*x)

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y, facecolor='blue', alpha=0.2)

# Display

plt.show()

Here we’ll shade the region by using the fill_between() method and we also pass the facecolor and alpha parameter to set the color and transparency of the plot respectively.

Output:

matplotlib fill_between alpha
fill_between(alpha=1)

Read: Matplotlib multiple bar chart

Matplotlib fill_between log scale

In this section, we’ll learn to fill the area under the curve in matplotlib python on a log scale. To create a log scale we set the scale of the axes to log.

The syntax to set the scale of the axes:

# For x-axis
matplotlib.pyplot.xscale('log')
# For y-axis
matplotlib.pyplot.yscale('log')

Let’s see an example:

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(-5, 5, 100)
y = np.sin(x)

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y)

# Log scale

plt.xscale('log')
plt.yscale('log')

# Display

plt.show()

Explanation:

  • We import the matplotlib.pyplot and numpy library.
  • Next, we create data points using numpy.
  • Then, we plot the x and y data points using the plot() method.
  • To fill the area between the curves, we use the fill_between() method.
  • To create a log scale, we set the scale of the axes.
  • To display the plot, use the show() method.

Output:

Matplotlib fill_between log scale
fill_between log scale

Read: Matplotlib scatter plot legend

Matplotlib fill_between legend

We’ll learn here to add a legend to the fill_between plot.

The following is the syntax:

matplotlib.pyplot.fill_between(x,y, y1, label=) 

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(-2, 2, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Plot

plt.plot(x, y1, color='k', label='Sin')
plt.plot(x, y2, color='k', label='Cos')

# fill_between

plt.fill_between(x, y1, y2, color='cyan', label='Area')

# Add legend

plt.legend()

# Display

plt.show()

Explanation:

  • We import matplotlib.pyplot and numpy library.
  • Create x, y1, and y2 data points using numpy.
  • To plot x, y1, and y2 data points, we use the plot() method.
  • fill_between() method is used to fill the area between the two curves.
  • To place a legend on the plot, we use the legend() method.
  • To display the figure, use the show() method.

Output:

matplotlib fill_between legend
fill_between(label=)

Read: Matplotlib 3D scatter

Matplotlib fill_between line color

Here we’ll learn how to change the line color with the fill_between method. To change the color of the line we have to pass the edgecolor parameter to the method.

The following is the syntax:

matplotlib.fill_between(x, y1, y2, edgecolor=None)

Source Code:

# Import Library

import matplotlib.pyplot as plt

# Define Data coordinates

x =  [0, 1, 2, 3, 4, 5]
y1 = [30, 60, 90, 120, 150, 180]
y2 = [20, 40, 60, 80, 100, 120]

# Shade the region

plt.fill_between(x, y1, y2, facecolor='pink', 
                 edgecolor='green')

# Show the plot

plt.show()

Explanation:

  • We import matplotlib.pyplot method.
  • Next, we define data coordinates x, y1, and y2.
  • To fill the area between the curves, we use the fill_between() method and we pass the facecolor parameter to set the color.
  • To change the line color with the fill_between() method, we pass the edgecolor argument to the method. Here we set the line color to green.

Output:

matplotlib fill_between line color
fill_between(edgecolor=None)

Read: Stacked Bar Chart Matplotlib

Matplotlib fill_between line width

Here we’ll learn how to change the linewidth with the fill_between method. Basically, the linewidth parameter draws a border around the fill between curves.

The following is the syntax:

matplotlib.fill_between(x, y1, y2, linewidth=None)

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(-3, 3, 1000)
y = np.sin(x)

# fill_between with linewidth

plt.fill_between(x, y, facecolor='orange', linewidth=15,     
                 edgecolor='k')

# Display


plt.show()

Explanation:

  • We define data coordinates using numpy.
  • To fill the area under the curve, we use the fill_between() method.
  • To set the face color and edge color of the plot we pass facecolor and edgecolor parameters and set their value orange and black respectively.
  • To change the width of the line or edges we pass the linewidth argument and set its value to 15. It creates a border around the curve.

Output:

matplotlib fil_between line width
fill_between(linewidth=15)

Read: Matplotlib two y axes

Matplotlib fill_between no edge

Here we are going to fill the area between or below the curves without edges. For this, we have to set linewidth to zero.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, linewidth=0)

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(-3, 3, 1000)
y = np.cos(x)

# fill_between no edges

plt.fill_between(x, y, facecolor='m', linewidth=0)

# Display

plt.show()

In the above example, we set the linewidth to zero and pass it to the fill_between method to get curves without edges.

Output:

matplotlib fill_between no edges
fill_between no edges

Read: Horizontal line matplotlib

Matplotlib fill_between edge

Here we are going to fill the area between or below the curves with edges. For this, we have to set linewidth to some value.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, color=None, linewidth=20)

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(-3, 3, 1000)
y = np.cos(x)

# Plot

plt.plot(x, y)

# fill_between no edges

plt.fill_between(x, y, color='yellow', linewidth=20)

# Display

plt.show()
  • In the above example, we use the fill_between() method to fill the area between the curve. Here we also set the color bypassing color argument to the method.
  • We increase the width bypassing the linewidth argument to the method, so we get the plot with edges.
matplotlib fill_between edge
fill_between(linewidth=20)

Read: Matplotlib plot bar chart

Matplotlib fill_between edgecolor

Here we see an example, of the edgecolor argument in the fill_between method.

Example:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(-3, 3, 1000)
y = np.cos(x)

# fill_between edge color

plt.fill_between(x, y, color='pink', edgecolor='red')

# Display

plt.show()
matplotlib fill_between edgecolor
fill_between(edgecolor=None)

Read: Python plot multiple lines using Matplotlib

Matplotlib fill_between datetime

Here we see an example of the fill_between() method in the datetime plot.

Source Code:

# Import Library

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Define Data

N = 500
dates = pd.date_range('2021-5-1', periods=N, freq='D')
x = np.linspace(0, 5, N)
data = pd.DataFrame({'A': np.cos(x), 'B': np.sin(x),
               'Date': dates})

#Plot

plt.plot_date(data['Date'], data['A'], '-')
plt.plot_date(data['Date'], data['B'], '-')

d = data['Date'].values

# fill_between

plt.fill_between(d, data['A'], data['B'],
                where=data['A'] <= data['B'],
                facecolor='yellow')

# Rotation of xticks

plt.xticks(rotation=45)

# Display


plt.show()
  • In the above example, we import import libraries such as matplotlib, numpy and pandas.
  • After this, we define data coordinates using date_range() method of pandas and sin() and cos() methods of numpy.
  • Then we the plt.plot_date() method to plot the date.
  • To fill the region between the curves of date plot we use the fill_between() method with where argument.
  • We also set the rotation of xtciks to avoid overlapping of dates on x-axis.
  • To display the plot, use show() method.
matplotlib fill_between datetime
fill_between()

Matplotlib fill between range

Here we see an example where we define data coordinate using the range() method of python. And to fill the region below the curve we use the fill_between() method.

The following is the syntax of the range() method:

range(start, stop, step)

Source Code:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates

x = range(3, 20, 2)
y = range(5, 22, 2)

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y, facecolor='green')

# Display

plt.show()
  • In the above source code, we import matplotlib.pyplot library.
  • Then we define data cordinates using range() method of python.
  • To plot the graph, use plot() method.
  • To fill the area below the curve, use fill_between() method.

Output:

matplotlib fill between range
range(start, stop, step)

Matplotlib fill between error bars

We know that how to display errors on the charts using error bars. Now, we are going to learn how we can use the fill_between method to shade error.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y-lower, y-upper)

The following are the parameters:

  • x: specify the x-coordinates of the plot.
  • lower: specify the bottom of the shaded area.
  • upper: specify the top of the shaded area.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates

x = range(8)
y = [10, 12, 13, 13, 20, 22, 23, 29]

# Define errors

y_lower_error = [8, 10, 11, 17, 18, 20, 21, 27]
y_upper_error = [12, 14, 15, 15, 17, 24, 25, 31]

# plot

plt.plot(x, y) 

# fill_between
 
plt.fill_between(x, y_lower_error, y_upper_error, 
                 facecolor='yellow') 

# Display

plt.show()

In the above example, we use the fill_between method to shade the errors, so we pass x, y_lower_error, y_upper_error, and facecolor to the method.

matplotlib fill between error bars
Shade Errors

Matplotlib fill between two vertical lines

We’ll learn to fill the area between two vertical lines or curves. To fill the area we use the fill_betweenx() method. Here the curves are defined by the points (y,x1) and (y,x2).

The following is the syntax:

matplotlib.pyplot.fill_betweenx(y, x1, x2, where=None, step=None,, interpolate=False, * , data=None, **kwargs)

Let’s see an example:

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 30, 0.2)
y = np.arange(30, 60, 0.2)

# Plot

plt.plot(x,y)

# Vertical line

plt.fill_betweenx(y, 15, 20, facecolor='green')

# Display

plt.show()

In the above source code, we use the fill_betweenx() method to fill the area between two vertical lines.

matplotlib fill between two vertical lines
fill_betweenx()

Matplotlib fill between two horizontal lines

We’ll learn to fill the area between two horizontal lines or curves. To fill the area we use the fill_between() method. Here the curves are defined by the points (x, y1) and (x, y2).

The following is the syntax:

matplotlib.pyplot.fill_betweenx(x, y1, y2, where=None, step=None,, interpolate=False, * , data=None, **kwargs)

Let’s see an example:

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 30, 0.2)
y = np.arange(30, 60, 0.2)

# Plot

plt.plot(x,y)

# Horizontal line

plt.fill_between(x, 30, 35, facecolor='m')

# Display

plt.show()

Explanation:

  • In the above example, we import matplotlib.pyplot and numpy library.
  • Next, we define data coordinates using arange() method of numpy.
  • Then to plot the line, use the plot() method.
  • To fill the area between two horizontal lines, use the fill_between() method.
  • To display the plot, use the show() method.
matplotlib fill between two horizontal lines
fill_between()

Matplotlib fill between on top

Here we’ll learn to fill color above the curve.

Let’s see examples related to this:

Example #1

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 50, 0.5)
y = x**5

# Plot

plt.plot(x,y)

# Top of curve

plt.fill_between(x, y, np.max(y), facecolor='chocolate')

# Display

plt.show()

In the above example, to fill the color on the top of curves, we use the fill_between() method with max(y) as a parameter.

matplotlib fill between top
max(y)

Example #2

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 50, 0.2)
y = np.cos(30*x)

# Plot

plt.plot(x,y)

# Top of the curve

plt.fill_between(x, y, 1, facecolor='lime')

# Display

plt.show()

In the above example, we use the fill_between method to fill color in the plot. Here the curves are defined by the points (x, y1) and (x, y2). To fill the area above the curve, we set y2 = 1.

Output:

matplotlib fill between on top
y2=1

Matplotlib fill_between pandas

We’ll learn to fill the area between the curves created using the Pandas DataFrame.

Source Code:

# Import Library

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Define Data

N = 100
dates = pd.date_range('2020-5-1', periods=N)
x = np.linspace(0, 10, N)
data = pd.DataFrame({'X': np.exp(x), 'Y': np.sin(x),
               'Date': dates})

# Plot

plt.plot_date(data['Date'], data['X'], '-')
plt.plot_date(data['Date'], data['Y'], '-')

d = data['Date'].values

# fill_between

plt.fill_between(d, data['X'], data['Y'],
                where=data['X'] > data['Y'],
                facecolor='lightgray')

# Rotation of xticks

plt.xticks(rotation=45)

# Display

plt.show()
matplotlib fill_between pandas
fill_between Pandas

Matplotlib fill between 0

We’ll learn to fill color between the area y1 and 0.

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 10, 0.5)
y = np.sin(30*x)

# Plot

plt.plot(x,y)

# Between y1 and 0

plt.fill_between(x, y, 0, facecolor='lightcoral')

# Display

plt.show()

In the above example, we use the fill_between() function to fill the color in the curve. Here we set y1 = y and y2 = 0 to fill between 0.

Output:

matplotlib fill between 0
fill between 0

Matplotlib fill between points

We’ll learn to fill the area between points. Here we define data coordinates in points.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Define data coordinates in ponts

X=[5, 10, 15, 20, 25, 30, 35]
Y=[35, 20, 10, 8, 6, 12, 15]

# Plot

plt.plot(Y,X,'ro-')

# fill_between points

plt.fill_betweenx(X, Y, 35, color='wheat') 

# Display

plt.show()
  • In the above example, we import matplotlib.pyplot library.
  • After this, we define data coordinates by defining points.
  • To plot the data, we use the plot() function.
  • To fill the color, use the fill_between() function where we set x= x, y1 = y and y2 =40.
matplotlib fill between points
fill_between()

Matplotlib fill between different colors

Here we’ll learn to fill the area between the curves with different colors depending upon conditions.

Let’s see an example to understand the concept:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 50, 0.2)
y = np.cos(30*x)

# Plot

plt.plot(x,y)

# Different colors

plt.fill_between(x, y, 1, where=(x>=20), facecolor='teal')

plt.fill_between(x, y, 1, where=(x<=20), facecolor='plum')

# Display

plt.show()
  • In the above example, we import the important libraries such as matplotlib.pyplot and numpy.
  • After this, we define data coordinates using numpy.
  • To plot the curves, use plot() method.
  • Then fill the area between the curves using fill_between() method and then we will set the color of the curves region depending upon the condition.
matplotlib fill between different colors
Different colors

Matplotlib fill between style

We’ll learn to fill a plot with different styles depending upon conditions. To fill with styles we use the hatch and facecolor arguments in the fill_between() method.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 80, 0.2)
y = np.sin(x)

# Plot

plt.plot(x,y)

# fill_between style

plt.fill_between(x, y, 1, where=(x>10) & (x<=20), hatch='\\\\', facecolor='lightgray')
plt.fill_between(x, y, 1, where=(x>20) & (x<=40), hatch='xx', facecolor='peachpuff')
plt.fill_between(x, y, 1, where=(x>40) & (x<=60), hatch='...', facecolor='honeydew')
plt.fill_between(x, y, 1, where=(x>60) & (x<=80), hatch='*', facecolor='thistle')
plt.fill_between(x, y, 1, where=(x<=10), hatch='o', facecolor='mistyrose')

# Display

plt.show()

Explanation:

  • In the above example, we import important libraries such as matplotlib.pyplot, and numpy.
  • Then we define data coordinates using arange() and sin() method s of numpy.
  • To plot the curves, use the plot() method.
  • To fill the region of the curve with different styles depending upon the condition, use hatch and facecolor arguments with the fill_between() method.
  • To visualize the plot on the user’s screen, use the show() method.

Output:

matplotlib fill between style
Different Styles

Matplotlib label for fill_between

We’ll see an example of the plot where we use the fill_between() function to fill the region under the curves and we also define the x-axis and y-axis label of the plot.

Source Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.linspace(20, 10, 50)
y = np.cos(45*x)

# Plot

plt.plot(x, y)

# fill_between

plt.fill_between(x, y, facecolor='pink')

# Labels

plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Display

plt.show()
  • Here we define data coordinates using linespace() and cos() methods of numpy.
  • Then we plot the curves, using the plot() method.
  • To fill the area between the regions, use the fill_between() method.
  • Then we set axes labels using xlabel() and ylabel() methods.
matplotlib label for fill_between
xlabel() and ylabel()

Matplotlib fill_between interpolate

Here we’ll learn about interpolate parameter of the fill_between() function. This parameter is used only when where parameter is used. This parameter is also used when two curves are crossing each other.

Setting interpolate argument to True will calculate the actual intersection point and extend the filled region up to this point.

The following is the syntax:

matplotlib.pyplot.fill_between(x, y, y1, where=None, interpolate=True)

Example:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data Coordinates

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
y = [6, 7.5, 8.3, 8, 9.2, 8.5, 9.4, 8.7, 8.8, 8.9, 7.4, 9.5, 5]
y1 = 8.9
z1 = np.array(y)
z2 = np.array([y1] * 13)

# Plot

plt.plot(x, y)

# Fill between

plt.fill_between(x, y, y1,
                 where=(z1 < z2),
                 color='maroon', interpolate=True)
plt.fill_between(x, y, 8.9,
                 where=(z1 >= z2),
                 color='cadetblue', interpolate=True)
# Display

plt.show()
matplotlib fill_between interpolate
fill_between(interpolate=True)

Matplotlib fill_between confidence interval

We’ll use the confidence interval with the fill_between() function. Firstly, we have to understand what does confidence interval means.

Confidence Interval is a range of estimates, defined by a lower bound and upper bound, for an unkown parameter.

The following is the syntax:

matplotlib.fill_between(x, (y-ci), (y+ci))

Here ci is the confidence interval.

Example:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates

x = np.arange(0, 20, 0.05)
y = np.cos(x)

# Define the confidence interval

ci = 0.05 * np.std(y) / np.mean(y)

# Plot

plt.plot(x, y)

# Plot the confidence interval

plt.fill_between(x, (y-ci), (y+ci), facecolor='gold', 
                 alpha=0.5)

plt.fill_between(x, (y-2*ci), (y+2*ci), 
                facecolor='springgreen', alpha=0.5)

plt.fill_between(x, (y-3*ci), (y+3*ci), facecolor='plum', 
                 alpha=0.2)

# Display

plt.show()

Explanation:

  • Here we import matplotlib.pyplot and numpy library.
  • Then we define data coordinates x and y using numpy.
  • Then we pass the y-ci and y+ci argument to the fill_between() method to define lower interval and upper interval around the function y respectively.
  • We also pass the facecolor and alpha arguments to the method.

Output:

matplotlib fill_between confidence interval
Confidence Interval

Matplotlib fill between standard deviation

Here we’ll plot the standard deviation with confidence interval. To find the standard deviation, use the std() method of numpy.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates


x = np.arange(0, 40, 0.05)
y = np.sin(x)

# Define the standard deviation

sd = np.std(y)

# Plot

plt.plot(x, y)

# Plot the Standard Deviation


plt.fill_between(x, (y-sd), (y+sd), facecolor='gold', alpha=0.5)

# Display

plt.show()

To plot a filled interval with the standard deviation and the lower and upper interval boundaries i.e. y-sd and y+sd around function values y, use the plt.fill_between(x, (y-sd), (y+sd)) function.

matplotlib fill between standard deviation
Standard Deviation

Matplotlib fill between x axis

We’ll learn to fill the region between a curve and the x-axis.

Example:

# Import Library


import matplotlib.pyplot as plt
import numpy as np

# Define Data Coordinates

x = np.linspace(-1, 1, 100)
y = np.cos(x)

# Plot

plt.plot(x, y)

# Fill the region with color


plt.fill_between(x, 0, y, facecolor='olive')

# Display the plot

plt.show()
  • Here we create x and y data coordinates using numpy.
  • Plot data coordintes using plot() method.
  • To fill the are between the curve and x-axis, use fill_between() function
  • To display the plot, use show() method.
matplotlib fill between x axis

Matplotlib fill between polygon

Here we learn to create a polygon and then fill the area between polygon using the fill_between() function.

Example:

# Import Library

from shapely.geometry import Polygon
import matplotlib.pyplot as plt

# Create Polygon

pol = Polygon([(0, 7),
   (1, 2),
   (6, 0),
   (4, 8) ])
x, y = pol.exterior.xy

# PLot

plt.plot(x, y)

# Fill between

plt.fill_between(x, y, facecolor='thistle')

# Display

plt.show()
  • Using x and y data points create polygon.
  • Get x and y, the exterior data, and the array using polygon.exterior.xy.
  • To plot the polygon, use plot() method.
  • To fill the area between polygon, use fill_between function.
matplotlib fill between polygon
Polygon

Matplotlib fill_between polar

Here we’ll draw a polar plot and fill the area between them using the fill_between method.

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data Coordinates

x = np.arange(0, 2, 1./200)*np.pi
y = abs(6*np.cos(4*x))
y1 = 2 + 0*x

# Plot Polar Coordinates


plt.polar(x, y, lw=3)
plt.polar(x, y1, lw=3)

# Fill Between

plt.fill_between(x, y, y1, facecolor='purple')

# Display

plt.show()
matplotlib fill_between polar
fill_between()

Read: Matplotlib increase plot size

Matplotlib fill_between animation

Here we are going to learn how to fill the area between the region of a plot with animations.

Let’s see an example:

# Interactive Mode

%matplotlib notebook

# Import Library

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# Define Data


X = np.arange(0, 40, 0.05)
Y = np.cos(X)
fig = plt.figure(figsize=(8, 4))
ax = plt.axes(xlim=(0,5), ylim=(-1,1.5))
line, = ax.plot([], [])

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = X[0:(i-1)]
    y = Y[0:(i-1)]
    line.set_data(x,y)
    p = plt.fill_between(x, y, 0, facecolor = 'firebrick', alpha=0.2)
    return line, p

# Animation

ani = animation.FuncAnimation(fig, animate, init_func=init, 
                               frames = 1000, interval=5)

# Display

plt.show()
  • In the above example, we firstly enable Interactive Mode.
  • Then we import numpy, pyplot and animation libraries.
  • Next, we define data coordinates using arange() and cos() methods of numpy.
  • plt.figure() method is used to create a figure.
  • To fill the region between curves, use fill_between() method.
  • By using animation.FuncAnimation() method we add animation to Plot.
  • Then, at last, we use the save() method to save a plot as a gif.
Fill Between
Animation

So, in this Python tutorial, we have discussed the “Matplotlib fill_between” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib fill_between
  • Matplotlib fill_between example
  • Matplotlib fill_between color
  • Matplotlib fill_between hatch
  • Matplotlib fill_between step
  • Matplotlib fill_between hatch color
  • Matplotlib fill between facecolor
  • Matplotlib fill_between hatch density
  • Matplotlib fill_between where
  • Matplotlib fill between three lines
  • Matplotlib fill between two curves
  • Matplotlib fill between scatter
  • Matplotlib fill between dashed
  • Matplotlib fill between circle
  • Matplotlib fill between two lines
  • Matplotlib fill_between alpha
  • Matplotlib fill_between log scale
  • Matplotlib fill_between legend
  • Matplotlib fill_between line color
  • Matplotlib fill_between line width
  • Matplotlib fill_between no edge
  • Matplotlib fill_between edge
  • Matplotlib fill_between edgecolor
  • Matplotlib fill_between datetime
  • Matplotlib fill between range
  • Matplotlib fill between error bars
  • Matplotlib fill between two vertical lines
  • Matplotlib fill between two horizontal lines
  • Matplotlib fill between on top
  • Matplotlib fill_between pandas
  • Matplotlib fill between 0
  • Matplotlib fill between points
  • Matplotlib fill between different colors
  • Matplotlib fill between style
  • Matplotlib label for fill_between
  • Matplotlib fill_between interpolate
  • Matplotlib fill_between confidence interval
  • Matplotlib fill between standard deviation
  • Matplotlib fill between x axis
  • Matplotlib fill between polygon
  • Matplotlib fill_between polar
  • Matplotlib fill_between animation