You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Manim Community:如何批量为公式中指定文本统一设置颜色

给Manim矩阵中所有"a"统一上色的方法

以下是几种无需手动逐个索引的简便实现方式:

方法一:拆分字符+颜色映射(精准控制单个字母)

通过substrings_to_isolate将所有"a"单独拆分为子对象,再用tex_to_color_map或set_color_by_tex统一设置颜色,仅改变字母"a"的颜色,不影响下标:

from manim import *

class Example(Scene):
    def construct(self):
        A = MathTex(
            r"A=",
            r"\begin{pmatrix}",
            r"a_{11} & a_{12} & \dots  & a_{1n}\\",
            r"a_{21} & a_{22} & \dots  & a_{2n}\\",
            r"\vdots & \vdots & \ddots & \vdots\\",
            r"a_{n1} & a_{n2} & \dots  & a_{nn}",
            r"\end{pmatrix}",
            substrings_to_isolate=["a"],
            tex_to_color_map={"a": RED}
        ).center()

        self.play(Write(A))

如果需要在创建对象后调整颜色,可改用:

A.set_color_by_tex("a", RED)

方法二:字符串替换(批量注入LaTeX颜色命令)

直接对TeX字符串进行批量替换,将所有"a"替换为带颜色命令的版本,适合长公式场景:

from manim import *

class Example(Scene):
    def construct(self):
        # 原始TeX字符串
        tex_content = r"""
        A=
        \begin{pmatrix}
        a_{11} & a_{12} & \dots  & a_{1n}\\
        a_{21} & a_{22} & \dots  & a_{2n}\\
        \vdots & \vdots & \ddots & \vdots\\
        a_{n1} & a_{n2} & \dots  & a_{nn}
        \end{pmatrix}
        """
        # 批量替换所有"a"为红色版本
        colored_tex = tex_content.replace("a", r"\textcolor{red}{a}")
        A = MathTex(colored_tex).center()

        self.play(Write(A))

方法三:遍历子对象(通用匹配逻辑)

如果需要更灵活的匹配规则(比如匹配包含"a"的特定模式),可遍历所有子对象并设置颜色:

from manim import *

class Example(Scene):
    def construct(self):
        A = MathTex(
            r"A=",
            r"\begin{pmatrix}",
            r"a_{11} & a_{12} & \dots  & a_{1n}\\",
            r"a_{21} & a_{22} & \dots  & a_{2n}\\",
            r"\vdots & \vdots & \ddots & \vdots\\",
            r"a_{n1} & a_{n2} & \dots  & a_{nn}",
            r"\end{pmatrix}"
        ).center()

        # 遍历子对象,匹配包含"a"的片段并上色
        for submob in A.submobjects:
            tex = submob.get_tex()
            if "a" in tex:
                # 若需仅给"a"上色,需先拆分(推荐用方法一);这里会给整个片段上色
                submob.set_color(RED)

        self.play(Write(A))

注意:方法三默认会给包含"a"的整个子对象(比如a_{11})上色,如果只想单独给字母"a"上色,优先使用方法一。

内容的提问来源于stack exchange,提问作者haifisch123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 13:37:05