Tracing a portion of a graph and moves along that portion using Manim updater

Submitted by Jhun Vert on Tue, 11/10/2020 - 08:24

This post is about Manim code for tracing a portion of a graph and assigning a dot to move along that portion. In this animation, we created a cubic graph with y = x3 - 3x2 + 2x + 1.5 and trace a portion of this curve between x = -0.3 and x = 2.2 then assign a point to move along this portion. I use this code for the derivation of length of arc in the xy-plane. See the full video here: https://www.youtube.com/watch?v=4t-_vJcGDGs

The Manim Code:

from manimlib.imports import *

class JVCubicGraph(GraphScene):
    # Configure the x- and y-axes
    CONFIG = {
        "x_min": -1,
        "x_max": 3,
        "y_min": -1,
        "y_max": 3,
        "graph_origin": 1 * DOWN + 2 * LEFT,
    }

    def construct(self):
        # Setup the xy-axes
        self.setup_axes(animate=True)

        # Define the cubic graph
        CubicGraph = self.get_graph(self.CubicGraphEq, color=BLUE, stroke_width=2)
        CubicGraphLabel = self.get_graph_label(CubicGraph, label="y = f(x)")

        # Initialize the left limit using the equation of cubic graph
        x_1 = -0.3
        y_1 = self.CubicGraphEq(x=x_1)
        LeftLimitLocation = self.coords_to_point(x_1,y_1) # coordinates (-0.3, 0.603)
        LeftLimit = Dot(LeftLimitLocation, color=YELLOW)
        LeftLimitLabel = TextMobject("$P_1(x_1, \\, y_1)$", color=YELLOW)\
            .next_to(LeftLimit, LEFT, buff=SMALL_BUFF)
        
        # Initialize the right limit to be at the left limit
        RightLimit = Dot(LeftLimitLocation, color=YELLOW)
        RightLimitLabel = TextMobject("$P_2(x_2, \\, y_2)$", color=YELLOW)\
            .next_to(RightLimit, RIGHT, buff=SMALL_BUFF)

        # Add updater to right limit
        def update_text(obj):
            obj.next_to(RightLimit, RIGHT, buff=SMALL_BUFF)
        RightLimitLabel.add_updater(update_text)

        # Define a highlighted portion of the cubic graph
        LengthOfArc = self.get_graph(
            self.CubicGraphEq, color=YELLOW, x_min=-0.3, x_max=2.2)

        # Animate
        self.play(ShowCreation(CubicGraph), Write(CubicGraphLabel))
        self.play(ShowCreation(LengthOfArc), run_time=1.5)
        self.play(ShowCreation(LeftLimit), Write(LeftLimitLabel))
        self.play(MoveAlongPath(RightLimit, LengthOfArc), run_time=2)
        self.play(Write(RightLimitLabel))
        self.wait(3)

    # Equation of cubic graph
    def CubicGraphEq(self, x):
        return(x**3-3*x**2+2*x+1.5)

Output Video:

Category