Search code examples
pythonanimationmanim

How to animate a sine wave with decreasing period?


I'm trying to animate a sine wave whose periodicity shrinks, as if the graph is getting 'squished' from the left and right edges (y=sin(ax)) for continuously increasing values of a). I've tried using ApplyPointwiseFunction:

from manim import *

class SineWave(Scene):
    def construct(self):
        # self.camera.frame.save_state()

        # create the axes
        axes = Axes(x_range=[-1, 10], y_range=[-1, 10])
        self.add(axes)

        # Create the graph
        graph = axes.plot(lambda x: np.sin(x), color=BLUE)

        self.play(ApplyPointwiseFunction(lambda x: x*2, graph))

But this obviously isn't the right approach.

Is there something I can do using ApplyPointwiseFunction or should I look elsewhere?


Solution

  • After more hours than I'd like to admit, I figured it out! The below code works. You can play with run_time and the multiplication factor (100) in set_value to change the speed of the animation.

    from manim import *
    
    class SineWave(Scene):
        def construct(self):
            # The ValueTracker functions as the constant `a` in `sin(ab)`.
            tracker = ValueTracker(0.1)
    
            # Create the graph
            sine_function = lambda x: np.sin(tracker.get_value() * x)
            sine_graph = always_redraw(lambda: FunctionGraph(
                sine_function,
                color=BLUE
            ))
            self.add(sine_graph)
    
            # Animate the sine wave from y=sin(0.1*x) to y=sin(10*x) over the course of 6 seconds.
            self.play(tracker.animate(run_time=6).set_value(tracker.get_value() * 100)),