Reputation: 305
I want to paint variables of MathTex element in different colors, but Manim seems to have problems with comlicated Latex expressions.
Here is my scene.
from manim import *
config.frame_width = 260
class Find_Path(Scene):
def construct(self):
obj = MathTex(r"minimize \quad \sum_{start}^{end}\frac{d_{i,i+1}}{v_{i,i+1}}",
font_size=1000, substrings_to_isolate="d" and "v")
obj.set_color_by_tex("d", YELLOW)
obj.set_color_by_tex("start", GREEN)
obj.set_color_by_tex("end", GREEN)
obj.set_color_by_tex("v", RED)
self.play(Write(obj))
self.wait(3)
Here is the result.
Specifically, I want to color d_{i,i+1}
in YELLOW
, v_{i,i+1}
in RED
, start
and end
in GREEN
.
Any advice? Frankly, I do not want to create several MathTex object in different colors and then arrange them.
Upvotes: 3
Views: 4639
Reputation: 3542
Late answer, but I encountered a similar issue and ended up here before finding the relevant section in the documentation.
Relevant section in documentation: Using index_labels
to work with complicated strings
An example with your special case:
from manim import *
config.frame_width = 8
config.frame_size = (1300, 1000)
class FindPath(Scene):
def construct(self):
# You can split the string in parts
minimize = r"minimize \quad "
summ = r"\sum_{start}^{end}"
frac = r"\frac{d_{i,i+1}}{v_{i,i+1}}"
tex = MathTex(minimize, summ, frac).shift(2 * UP)
# Observe first level labels
tex_ = tex.copy().next_to(tex, DOWN)
self.add(index_labels(tex_, color=YELLOW))
# Observe second level labels
tex__ = tex_.copy().next_to(tex_, DOWN)
for part in tex__:
self.add(index_labels(part, color=YELLOW))
# Finally you can color accordingly
tex[1][0:3].set_fill(color=GREEN)
tex[1][4:9].set_fill(color=GREEN)
tex[2][0:6].set_fill(color=YELLOW)
tex[2][7:13].set_fill(color=RED)
self.add(tex, tex_, tex__)
Upvotes: 2
Reputation: 8260
Manim does a bunch of tex rewriting under the covers, and it seems that over
is preferred to frac
because of that rewriting.
I was able to apply the colors that you wanted (although I suspect you didn't want the sum symbol colored) with:
from manim import *
class Find_Path(Scene):
def construct(self):
obj1 = MathTex(r"\text{minimize}", r"\quad \sum_{\text{start}}^{\text{end}}")
obj2 = MathTex(r"d_{i,i+1}", r"\over", r"v_{i,i+1}")
obj1.set_color_by_tex("start", GREEN)
obj1.set_color_by_tex("end", GREEN)
obj2.move_to(obj1, RIGHT)
obj2.shift(1.5 * RIGHT)
obj2[0].set_color(YELLOW)
obj2[2].set_color(RED)
self.play(AnimationGroup(Write(obj1), Write(obj2)))
self.wait(3)
but I had to resort to separate objects. Worse still, I aligned them by hand with a fudge factor.
Upvotes: 2