Skip to content

Instantly share code, notes, and snippets.

@hkarl
Created April 4, 2024 09:51
Show Gist options
  • Save hkarl/9405da78c41557eb795feda61072d641 to your computer and use it in GitHub Desktop.
Save hkarl/9405da78c41557eb795feda61072d641 to your computer and use it in GitHub Desktop.
Animate plot_line_graph in Manim
from manim import *
from pprint import pprint as pp
class AnimatedLineGraphAxes(Axes):
pass
def plot_line_graph(self, *args, **kwargs):
try:
x_range = kwargs.pop("x_range")
# we do not want vertex dots in this case; maybe change in future
# to have vertex dots only at original, but not at interpolated points?
add_vertex_dots = kwargs.pop("add_vertex_dot", False)
add_vertex_dots = False
x_values = args[0]
y_values = args[1]
# cut off unnecessary values from x
try:
# do we need to interpolate?
endindex = next( i for i, x in enumerate(x_values) if x >= x_range[1])
# TODO: easy to add a slot for another interpolation function here ...
if x_values[endindex] is not x_range[1]:
x_values.insert(endindex, x_range[1])
y_values.insert(endindex, y_values[endindex-1])
x_values = x_values[0:endindex+1]
y_values = y_values[0:endindex+1]
except StopIteration:
pass
graph = super().plot_line_graph(x_values, y_values, add_vertex_dots=add_vertex_dots, **kwargs)
except KeyError:
# just pass call to superclass, no modification needed
graph = super().plot_line_graph(*args, **kwargs)
return graph
class AnimatedPlot(Scene):
def construct(self):
tvalues = [0, 2, 4, 6, 8, 10]
yvalues = [52, 64, 57, 45, 57, 43]
timereference = ValueTracker(0)
def myFunction(x):
return x**2 + 5
# axes = # always_redraw (lambda: AnimatedAxes(
axes = AnimatedLineGraphAxes(
x_range=[0, 10],
y_range=[0, 100],
axis_config={"color": BLUE},
)# )
graph = always_redraw(lambda: axes.plot(myFunction,
x_range=[0, timereference.get_value()],
color=WHITE))
lg = always_redraw(lambda: axes.plot_line_graph(tvalues, yvalues,
# x_range=[5 - 0.5*timereference.get_value(), 5+ 0.5*timereference.get_value()],
x_range=[0, timereference.get_value()],
line_color=BLUE))
self.add(axes, graph, lg)
# Animate the graph
self.play(
timereference.animate.set_value(10),
run_time=2,
rate_func=linear,
)
self.wait(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment