Search code examples
pythonlistmatplotlibgraphintegral

Integration of a curve generated using matplotlib


I have generated a graph using basic function -

plt.plot(tm, o1)

tm is list of all x coordinates and o1 is a list of all y coordinates

NOTE

there is no specific function such as y=f(x), rather a certain y value remains constant for a given range of x.. see figure for clarity

My question is how to integrate this function, either using the matplotlib figure or using the lists (tm and o1)

graph


Solution

  • The integral corresponds to computing the area under the curve. The most easy way to compute (or approximate) the integral "numerically" is using the rectangle rule which is basically approximating the area under the curve by summing area of rectangles (see https://en.wikipedia.org/wiki/Numerical_integration#Quadrature_rules_based_on_interpolating_functions).

    Practically in your case, it quite straightforward since it is a step function. First, I recomment to use numpy arrays instead of list (more handy for numerical computing):

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.array([0,1,3,4,6,7,8,11,13,15])
    y = np.array([8,5,2,2,2,5,6,5,9,9])
    
    plt.plot(x,y)
    

    Then, we compute the width of rectangles using np.diff():

    w = np.diff(x)
    

    Then, the height of the same rectangles (multiple possibilities exist):

    h = y[:-1]
    

    Here I chose the 2nd value of each two successive y values. the top right angle of rectangle is on the curve. You can choose the mean value of each two successive y values h = (y[1:]+y[:-1])/2 in which the middle of the top of the rectangle coincide with the curve.

    Then , you will need to multiply and sum:

    area = (w*h).sum()