Search code examples
latexmanim

How can I only color exponents in MathTex?


When using Manim, how can I only color the exponents of a number in a MathTex object?

In the formula I want to color, all "1"s are written as powers.

equation = r"\frac{6}{4^1-2}-\frac{5}{4^1+1}=2"

I have tried doing:

obj = MathTex(equation, substrings_to_isolate="^1")
obj.set_color_by_tex("1", RED)
self.play(Write(obj))

But when executing the code, I get an error:

LaTeX compilation error: Argument of \align* has an extra }.
Context of error:

\begin{document}

 -> \begin{align*}

  -2}-\frac{5}{4

 \end{align*}

Solution

  • The way Manim works when splitting LaTeX code either with isolate..., double braces, as separate substrings or any other option is, that it sends the individual fragments to LaTeX for rendering.

    However, some LaTeX commands like \frac cannot have their arguments split, because the resulting code is no valid LaTeX code anymore. One way is to use a \over b instead of \frac{a}{b}, but even that is not guaranteed to work flawlessly.

    I would say that automation is not worth the effort most of the time, so you could just count the corresponding index position of your glyphs to be highlighted, the function self.add(index_labels()) can help you here further:

    class testMathColor(Scene):
        def construct(self):
            matht9 = MathTex(
                r"\frac{6}{4^1-2}-\frac{5}{4^1+1}=2", 
            ).move_to([0, 0, 0])
            # uncomment to find indices
            self.add(matht9, index_labels(matht9[0]).set_color(RED).shift(0.15*UP))
            #matht9.set_color_by_tex("1", RED)
            #self.play(Write(matht9, run_time=1))
    

    enter image description here

    class testMathColor(Scene):
        def construct(self):
            matht9 = MathTex(
                r"\frac{6}{4^1-2}-\frac{5}{4^1+1}=2", 
            ).move_to([0, 0, 0])
            # uncomment to find indices
            #self.add(matht9, index_labels(matht9[0]).set_color(RED).shift(0.15*UP))
            for i in [3,10]:
                matht9[0][i].set_color(RED)
            self.play(Write(matht9, run_time=1))
    

    enter image description here

    Come over to Discord to learn more about other ways how to isolate and color parts of equations and/or in general about Manim.