55

I want to use matplotlib to illustrate the definite integral between two regions: x_0, and x_1.

How can I shade a region under a curve in matplotlib from x=-1, to x=1 given the following plot

import numpy as np
from matplotlib import pyplot as plt
def f(t):
    return t * t

t = np.arange(-4,4,1/40.)
plt.plot(t,f(t))
Georgy
  • 9,972
  • 7
  • 57
  • 66
lukecampbell
  • 14,118
  • 4
  • 32
  • 32
  • I think fill_between will work. t = np.arange(-4,4,1/40.) plt.plot(t,f(t)) plt.fill_between(t,f(t),color='green') – Golden Lion Sep 29 '21 at 17:49

3 Answers3

62

The final answer I came up with is to use fill_between.

I thought there would have been a simple shade between type method, but this does exactly what I want.

section = np.arange(-1, 1, 1/20.)
plt.fill_between(section,f(section))
Azat Ibrakov
  • 8,514
  • 9
  • 36
  • 44
lukecampbell
  • 14,118
  • 4
  • 32
  • 32
26

Check out fill. Here's an example on filling a constrained region.

gspr
  • 10,861
  • 3
  • 41
  • 72
1

A good way to do this a way that fit our datas is to use the fill_between function from pyplot.

To fill the desired area under the curve, i recommend using the where argument that provide a filter that fit your data:

import numpy as np
from matplotlib import pyplot as plt

def f(t):
    return t * t

t = np.arange(-4,4,1/40)

#Print the curve
plt.plot(t,f(t))

#Fill under the curve
plt.fill_between(
        x= t, 
        y1= f(t), 
        where= (-1 < t)&(t < 1),
        color= "b",
        alpha= 0.2)
        
plt.show()

You can play around with alpha (opacity) et color to make it look better. Here is the desired result :

enter image description here

The document of fill_between is available here : https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.fill_between.html