Search code examples
pythonmatplotlibmathdifferential-equations

Animate movement of Tangent line across graph


Background

Hello - I'm a new math's teacher and I've thought on how to illustrate the concept of derivatives. I would like to make a gif or a video (don't really care which one) of a tangent line moving along a graph.

I've tried many different ways, and most of the videos/ posts I've read, shows a graph being constructed as x changes... This is not really what I'm looking for, as following those videos I can also construct my graph. But I want a straight line changing its slope at each point along the graph.

# Define parabola
def f(x):
    return 5*x**3-2*x**2-2*x

# Define parabola derivative
def slope(x):
    return 15*x**2-4*x-2

# Define tangent line
def line(x, x1, y1):
    return slope(x1)*(x - x1) + y1

My question

are there any good examples of how this might be done? maybe videos or codes I could look at for inspiration?

I know my question is a bit vague, but thanks in advance


Solution

  • You could use the FuncAnimation function that matplotlib provides (see doc here).

    Below is an example with the code you provided:

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.animation import FuncAnimation
    
    # Define parabola
    def f(x):
        return 5*x**3-2*x**2-2*x
    
    # Define parabola derivative
    def slope(x):
        return 15*x**2-4*x-2
    
    # Define tangent line
    def line(x, x1, y1):
        return slope(x1)*(x - x1) + y1
    
    
    ###Set up animation###
    fig, ax = plt.subplots()
    range_x=np.linspace(-1,1,100,endpoint=True)
    range_slope=np.linspace(-1,1,100,endpoint=True)
    plt.plot(range_x, f(range_x),'ro',label='Parabola')
    ln_slope,=plt.plot([],[],'tab:blue',label='Tangent',lw=3.5)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.legend(loc='upper right')
    
    
    def init():
        ax.set_xlim(-1,1)
        ax.set_ylim(-6, 3)
        
        return ln_slope,
    
    
    def update(frame):
        ydata=line(range_slope,range_x[frame],f(range_x[frame]))
    
        ln_slope.set_data(range_slope, ydata)
        return ln_slope,
    
    ani = FuncAnimation(fig, update, frames=100,init_func=init, blit=True)
    plt.show()
    

    And the output gives:

    enter image description here