Tutorial: Plotting a Graph

Draw sine and cosine on one pair of axes, label them, mark a point, and send a dot along a curve.

1. The axes

from pymations import *

axes = Axes(
    x_range=[-7, 7, 1],
    y_range=[-1.5, 1.5, 1],
    x_length=12,
    y_length=4,
    axis_config={"color": GREEN},
    tips=False,
)
play(Create(axes), run_time=1.5)

x_range goes from -7 to 7 with a tick every 1. x_length=12 makes the x axis 12 units long on screen, nearly the whole width.

2. Two curves and their labels

sin_graph = axes.plot(lambda x: np.sin(x), color=BLUE)
cos_graph = axes.plot(lambda x: np.cos(x), color=RED)

sin_label = MathTex(r"\sin(x)", color=BLUE).next_to(axes.c2p(-7, 1), UR)
cos_label = MathTex(r"\cos(x)", color=RED).next_to(axes.c2p(7, 1), UL)

play(Create(sin_graph), Write(sin_label), run_time=2)
play(Create(cos_graph), Write(cos_label), run_time=2)

axes.plot turns a Python function into a curve. axes.c2p(-7, 1) is the point at x = -7, y = 1 on the axes, and next_to(..., UR) puts the label just above and to the right of it.

3. Mark x = 2π

marker = DashedLine(axes.c2p(TAU, -1.2), axes.c2p(TAU, 1.2), color=YELLOW)
marker_label = MathTex(r"x = 2\pi", color=YELLOW, font_size=36).next_to(marker, DOWN, buff=0.1)

play(Create(marker), FadeIn(marker_label, shift=DOWN * 0.3))
wait()

TAU is 2π. FadeIn(..., shift=DOWN * 0.3) slides the label down a little as it appears.

4. A dot that rides the curve

dot = Dot(axes.c2p(-7, np.sin(-7)), color=YELLOW)
play(GrowFromCenter(dot))
play(MoveAlongPath(dot, sin_graph), run_time=4, rate_func=linear)
wait()

MoveAlongPath moves the dot along the curve from its start to its end. rate_func=linear keeps the speed steady, instead of starting and ending gently.

The whole file

from pymations import *

axes = Axes(x_range=[-7, 7, 1], y_range=[-1.5, 1.5, 1], x_length=12, y_length=4,
            axis_config={"color": GREEN}, tips=False)
sin_graph = axes.plot(lambda x: np.sin(x), color=BLUE)
cos_graph = axes.plot(lambda x: np.cos(x), color=RED)
sin_label = MathTex(r"\sin(x)", color=BLUE).next_to(axes.c2p(-7, 1), UR)
cos_label = MathTex(r"\cos(x)", color=RED).next_to(axes.c2p(7, 1), UL)
marker = DashedLine(axes.c2p(TAU, -1.2), axes.c2p(TAU, 1.2), color=YELLOW)
marker_label = MathTex(r"x = 2\pi", color=YELLOW, font_size=36).next_to(marker, DOWN, buff=0.1)
dot = Dot(axes.c2p(-7, np.sin(-7)), color=YELLOW)

play(Create(axes), run_time=1.5)
play(Create(sin_graph), Write(sin_label), run_time=2)
play(Create(cos_graph), Write(cos_label), run_time=2)
play(Create(marker), FadeIn(marker_label, shift=DOWN * 0.3))
play(GrowFromCenter(dot))
play(MoveAlongPath(dot, sin_graph), run_time=4, rate_func=linear)
wait()

Try this

  • Add tan: axes.plot(lambda x: np.tan(x), x_range=[-1.4, 1.4]). Without the range, it shoots off to infinity.
  • Replace the axes with NumberPlane() for a grid behind the curves.
  • Make the dot follow a ValueTracker instead, so you can stop it anywhere.