ZhangZhihui's Blog  

https://docs.manim.community/en/stable/guides/using_text.html

 

The TeX mobject can accept multiple strings as arguments. Afterwards you can refer to the individual parts either by their index (like tex[1]), or by using set_color_by_tex().

 

class LaTeXSubstrings(Scene):
    def construct(self):
        tex = Tex('Hello', r'$\bigstar$', r'\LaTeX', font_size=144)
        tex.set_color_by_tex(r'$\bigstar$', RED)
        tex[2].set_color(YELLOW)
        self.add(tex)

 

1

 

Because set_color_by_tex() requires an exact match, it cannot directly target a token inside a string that was passed as a single argument. To color every x in a formula, use substrings_to_isolate to split the string at each occurrence first:

class CorrectLaTeXSubstringColoring(Scene):
    def construct(self):
        equation = MathTex(
            r"e^{x} = x^0 + x^1 + \frac{1}{2} x^2 + \frac{1}{6} x^3 + \cdots + \frac{1}{n!} x^n + \cdots",
            substrings_to_isolate="x"
        )
        equation.set_color_by_tex("x", YELLOW)
        self.add(equation)

 

1

 

Each isolated occurrence of x becomes its own sub-mobject that set_color_by_tex() can match exactly. If one of the substrings_to_isolate is in a sub or superscript, it needs to be enclosed by curly brackets.

Note that Manim also supports a custom syntax that allows splitting a TeX string into substrings easily: simply enclose parts of your formula that you want to isolate with double braces. In the string MathTex(r"{{ a^2 }} + {{ b^2 }} = {{ c^2 }}"), the rendered mobject will consist of the substrings a^2, +, b^2, =, and c^2. This makes transformations between similar text fragments easy to write using TransformMatchingTex.

For Manim to recognise a {{ as a group opener, it must appear either at the very start of the string or be immediately preceded by a whitespace character. This means that {{ embedded directly after non-whitespace LaTeX — such as \frac{{{n}}}{k} or a^{{2}} — is left untouched, which prevents accidental splitting of ordinary nested-brace expressions. To stop a leading {{ from being treated as a group opener, insert a space between the two braces: {{ ... }} → { { ... } }.

 

posted on 2026-05-14 16:54  ZhangZhihuiAAA  阅读(29)  评论(0)    收藏  举报