Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add `font_size` parameter for `Tex` and `Text` mobjects. (#1694)

Laith Bahodif7ed88008b9f
diff --git a/docs/source/examples.rst b/docs/source/examples.rst
index b0ff789f0..ae67dc88f 100644
--- a/docs/source/examples.rst
+++ b/docs/source/examples.rst
@@ -457,8 +457,8 @@ Special Camera Settings
image = ImageMobject(np.uint8([[0, 100, 30, 200],
[255, 0, 5, 33]]))
image.height = 7
- frame_text = Text("Frame", color=PURPLE).scale(1.4)
- zoomed_camera_text = Text("Zoomed camera", color=RED).scale(1.4)
+ frame_text = Text("Frame", color=PURPLE, font_size=67)
+ zoomed_camera_text = Text("Zoomed camera", color=RED, font_size=67)
self.add(image, dot)
zoomed_camera = self.zoomed_camera
@@ -627,8 +627,7 @@ Advanced Projects
self.wait()
grid = NumberPlane()
- grid_title = Tex("This is a grid")
- grid_title.scale(1.5)
+ grid_title = Tex("This is a grid", font_size=72)
grid_title.move_to(transform_title)
self.add(grid, grid_title) # Make sure title is on top of grid
diff --git a/docs/source/tutorials/building_blocks.rst b/docs/source/tutorials/building_blocks.rst
index cd883c985..c159d0e26 100644
--- a/docs/source/tutorials/building_blocks.rst
+++ b/docs/source/tutorials/building_blocks.rst
@@ -385,9 +385,9 @@ and :meth:`~.Mobject.get_start`. Here is an example of some important coordinate
point_start= a.get_start()
point_end = a.get_end()
point_center = a.get_center()
- self.add(Text(f"a.get_start() = {np.round(point_start,2).tolist()}").scale(0.5).to_edge(UR).set_color(YELLOW))
- self.add(Text(f"a.get_end() = {np.round(point_end,2).tolist()}").scale(0.5).next_to(self.mobjects[-1],DOWN).set_color(RED))
- self.add(Text(f"a.get_center() = {np.round(point_center,2).tolist()}").scale(0.5).next_to(self.mobjects[-1],DOWN).set_color(BLUE))
+ self.add(Text(f"a.get_start() = {np.round(point_start,2).tolist()}", font_size=24).to_edge(UR).set_color(YELLOW))
+ self.add(Text(f"a.get_end() = {np.round(point_end,2).tolist()}", font_size=24).next_to(self.mobjects[-1],DOWN).set_color(RED))
+ self.add(Text(f"a.get_center() = {np.round(point_center,2).tolist()}", font_size=24).next_to(self.mobjects[-1],DOWN).set_color(BLUE))
self.add(Dot(a.get_start()).set_color(YELLOW).scale(2))
self.add(Dot(a.get_end()).set_color(RED).scale(2))
diff --git a/docs/source/tutorials/using_text.rst b/docs/source/tutorials/using_text.rst
index 90b549319..fac7c91ae 100644
--- a/docs/source/tutorials/using_text.rst
+++ b/docs/source/tutorials/using_text.rst
@@ -32,7 +32,7 @@ Here is a simple *Hello World* animation.
class HelloWorld(Scene):
def construct(self):
- text = Text("Hello world").scale(3)
+ text = Text("Hello world", font_size=144)
self.add(text)
You can also use :class:`~.MarkupText` which allows the use of PangoMarkup
@@ -161,7 +161,7 @@ be an iterable of any length:
class GradientExample(Scene):
def construct(self):
- t = Text("Hello", gradient=(RED, BLUE, GREEN)).scale(2)
+ t = Text("Hello", gradient=(RED, BLUE, GREEN), font_size=96)
self.add(t)
You can also use :attr:`~.Text.t2g` for gradients with specific
@@ -223,8 +223,8 @@ You can disable ligatures by passing ``disable_ligatures`` to
class DisableLigature(Scene):
def construct(self):
- li = Text("fl ligature").scale(2)
- nli = Text("fl ligature", disable_ligatures=True).scale(2)
+ li = Text("fl ligature",font_size=96)
+ nli = Text("fl ligature", disable_ligatures=True, font_size=96)
self.add(Group(li, nli).arrange(DOWN, buff=.8))
.. _iterating-text:
@@ -242,7 +242,7 @@ For example, you can set each letter to different color by iterating it.
class IterateColor(Scene):
def construct(self):
- text = Text("Colors").scale(2)
+ text = Text("Colors", font_size=96)
for letter in text:
letter.set_color(random_bright_color())
self.add(text)
@@ -274,7 +274,8 @@ and further references about PangoMarkup.
text = MarkupText(
f'<span underline="double" underline_color="green">double green underline</span> in red text<span fgcolor="{YELLOW}"> except this</span>',
color=RED,
- ).scale(0.7)
+ font_size=34
+ )
self.add(text)
.. _rendering-with-latex:
@@ -292,7 +293,7 @@ For example,
class HelloLaTeX(Scene):
def construct(self):
- tex = Tex(r"\LaTeX").scale(3)
+ tex = Tex(r"\LaTeX", font_size=144)
self.add(tex)
.. note::
@@ -315,8 +316,8 @@ similar effect with :class:`~.Tex` by enclosing your formula with ``$`` symbols:
class MathTeXDemo(Scene):
def construct(self):
- rtarrow0 = MathTex(r"\xrightarrow{x^6y^8}").scale(2)
- rtarrow1 = Tex(r"$\xrightarrow{x^6y^8}$").scale(2)
+ rtarrow0 = MathTex(r"\xrightarrow{x^6y^8}", font_size=96)
+ rtarrow1 = Tex(r"$\xrightarrow{x^6y^8}$", font_size=96)
self.add(VGroup(rtarrow0, rtarrow1).arrange(DOWN))
@@ -332,7 +333,7 @@ as the ``mathtt`` math-text type or the ``looparrowright`` arrow.
class AMSLaTeX(Scene):
def construct(self):
- tex = Tex(r'$\mathtt{H} \looparrowright$ \LaTeX').scale(3)
+ tex = Tex(r'$\mathtt{H} \looparrowright$ \LaTeX', font_size=144)
self.add(tex)
On the Manim side, the :class:`~.Tex` class also accepts attributes to
@@ -345,7 +346,7 @@ color of the TeX mobject.
class LaTeXAttributes(Scene):
def construct(self):
- tex = Tex(r'Hello \LaTeX', color=BLUE).scale(3)
+ tex = Tex(r'Hello \LaTeX', color=BLUE, font_size=144)
self.add(tex)
Extra LaTeX Packages
@@ -363,7 +364,7 @@ we have to add it manually.
def construct(self):
myTemplate = TexTemplate()
myTemplate.add_to_preamble(r"\usepackage{mathrsfs}")
- tex = Tex(r'$\mathscr{H} \rightarrow \mathbb{H}$}', tex_template=myTemplate).scale(3)
+ tex = Tex(r'$\mathscr{H} \rightarrow \mathbb{H}$}', tex_template=myTemplate, font_size=144)
self.add(tex)
Substrings and parts
@@ -379,7 +380,7 @@ of the ``\bigstar`` using :func:`~.set_color_by_tex`:
class LaTeXSubstrings(Scene):
def construct(self):
- tex = Tex('Hello', r'$\bigstar$', r'\LaTeX').scale(3)
+ tex = Tex('Hello', r'$\bigstar$', r'\LaTeX', font_size=144)
tex.set_color_by_tex('igsta', RED)
self.add(tex)
@@ -438,7 +439,7 @@ ready for you to use. These templates will all work in math mode:
class LaTeXMathFonts(Scene):
def construct(self):
- tex = Tex(r'$x^2 + y^2 = z^2$', tex_template=TexFontTemplates.french_cursive).scale(3)
+ tex = Tex(r'$x^2 + y^2 = z^2$', tex_template=TexFontTemplates.french_cursive, font_size=144)
self.add(tex)
Manim also has a :class:`~.TexTemplateLibrary` containing the TeX
@@ -453,7 +454,7 @@ should use :class:`~.Text` instead.
class LaTeXTemplateLibrary(Scene):
def construct(self):
- tex = Tex('Hello 你好 \\LaTeX', tex_template=TexTemplateLibrary.ctex).scale(3)
+ tex = Tex('Hello 你好 \\LaTeX', tex_template=TexTemplateLibrary.ctex, font_size=144)
self.add(tex)
@@ -469,5 +470,5 @@ when typesetting multiline formulae:
class LaTeXAlignEnvironment(Scene):
def construct(self):
- tex = MathTex(r'f(x) &= 3 + 2 + 1\\ &= 5 + 1 \\ &= 6').scale(2)
+ tex = MathTex(r'f(x) &= 3 + 2 + 1\\ &= 5 + 1 \\ &= 6', font_size=96)
self.add(tex)
diff --git a/example_scenes/basic.py b/example_scenes/basic.py
index 6d5e217f0..b6c5f5188 100644
--- a/example_scenes/basic.py
+++ b/example_scenes/basic.py
@@ -34,8 +34,7 @@ class OpeningManim(Scene):
self.wait()
grid = NumberPlane()
- grid_title = Tex("This is a grid")
- grid_title.scale(1.5)
+ grid_title = Tex("This is a grid", font_size=72)
grid_title.move_to(transform_title)
self.add(grid, grid_title) # Make sure title is on top of grid
diff --git a/manim/animation/animation.py b/manim/animation/animation.py
index dea0cbf0c..7ecb2d6bb 100644
--- a/manim/animation/animation.py
+++ b/manim/animation/animation.py
@@ -79,9 +79,9 @@ class Animation:
self.add(groups)
# Label groups
- self.add(Text("lag_ratio = ").scale(0.7).next_to(groups, UP, buff=1.5))
+ self.add(Text("lag_ratio = ", font_size=36).next_to(groups, UP, buff=1.5))
for group, ratio in zip(groups, ratios):
- self.add(Text(str(ratio)).scale(0.7).next_to(group, UP))
+ self.add(Text(str(ratio), font_size=36).next_to(group, UP))
#Animate groups with different lag_ratios
self.play(AnimationGroup(*[
diff --git a/manim/animation/creation.py b/manim/animation/creation.py
index 44de8c843..137d86650 100644
--- a/manim/animation/creation.py
+++ b/manim/animation/creation.py
@@ -15,17 +15,17 @@ r"""Animate the display or removal of a mobject from a scene.
s6 = Square()
s7 = Square()
VGroup(s5, s6, s7).set_x(0).arrange(buff=2.6).shift(2 * DOWN)
- t1 = Text("Write").scale(0.5).next_to(s1, UP)
- t2 = Text("AddTextLetterByLetter").scale(0.5).next_to(s2, UP)
- t3 = Text("Create").scale(0.5).next_to(s3, UP)
- t4 = Text("Uncreate").scale(0.5).next_to(s4, UP)
- t5 = Text("DrawBorderThenFill").scale(0.5).next_to(s5, UP)
- t6 = Text("ShowIncreasingSubsets").scale(0.45).next_to(s6, UP)
- t7 = Text("ShowSubmobjectsOneByOne").scale(0.45).next_to(s7, UP)
+ t1 = Text("Write", font_size=24).next_to(s1, UP)
+ t2 = Text("AddTextLetterByLetter", font_size=24).next_to(s2, UP)
+ t3 = Text("Create", font_size=24).next_to(s3, UP)
+ t4 = Text("Uncreate", font_size=24).next_to(s4, UP)
+ t5 = Text("DrawBorderThenFill", font_size=24).next_to(s5, UP)
+ t6 = Text("ShowIncreasingSubsets", font_size=22).next_to(s6, UP)
+ t7 = Text("ShowSubmobjectsOneByOne", font_size=22).next_to(s7, UP)
self.add(s1, s2, s3, s4, s5, s6, s7, t1, t2, t3, t4, t5, t6, t7)
- texts = [Text("manim").scale(0.6), Text("manim").scale(0.6)]
+ texts = [Text("manim", font_size=29), Text("manim", font_size=29)]
texts[0].move_to(s1.get_center())
texts[1].move_to(s2.get_center())
self.add(*texts)
@@ -275,13 +275,13 @@ class Write(DrawBorderThenFill):
class ShowWrite(Scene):
def construct(self):
- self.play(Write(Text("Hello").scale(3)))
+ self.play(Write(Text("Hello", font_size=144)))
.. manim:: ShowWriteReversed
class ShowWriteReversed(Scene):
def construct(self):
- self.play(Write(Text("Hello").scale(3), reverse=True))
+ self.play(Write(Text("Hello", font_size=144), reverse=True))
"""
def __init__(
diff --git a/manim/constants.py b/manim/constants.py
index 8622e881b..8200ffdca 100644
--- a/manim/constants.py
+++ b/manim/constants.py
@@ -59,6 +59,7 @@ __all__ = [
"DEFAULT_POINT_DENSITY_2D",
"DEFAULT_POINT_DENSITY_1D",
"DEFAULT_STROKE_WIDTH",
+ "DEFAULT_FONT_SIZE",
"PI",
"TAU",
"DEGREES",
@@ -189,6 +190,7 @@ DEFAULT_WAIT_TIME: float = 1.0
DEFAULT_POINT_DENSITY_2D: int = 25
DEFAULT_POINT_DENSITY_1D: int = 10
DEFAULT_STROKE_WIDTH: int = 4
+DEFAULT_FONT_SIZE: float = 48
# Mathematical constants
PI: float = np.pi
diff --git a/manim/mobject/coordinate_systems.py b/manim/mobject/coordinate_systems.py
index b080b58ac..7f89823ac 100644
--- a/manim/mobject/coordinate_systems.py
+++ b/manim/mobject/coordinate_systems.py
@@ -46,6 +46,7 @@ from ..utils.color import (
invert_color,
)
from ..utils.config_ops import merge_dicts_recursively, update_dict_recursively
+from ..utils.deprecation import deprecated_params
from ..utils.simple_functions import binary_search
from ..utils.space_ops import angle_of_vector
@@ -70,7 +71,7 @@ class CoordinateSystem:
y_length=5.5,
axis_config={
"numbers_to_include": np.arange(0, 1 + 0.1, 0.1),
- "number_scale_value": 0.5,
+ "font_size": 24,
},
tips=False,
)
@@ -96,7 +97,7 @@ class CoordinateSystem:
# spaces between braces to prevent SyntaxError
r"Graphs of $y=x^{ {1}\over{n} }$ and $y=x^n (n=1,2,3,...,20)$",
include_underline=False,
- scale_factor=0.85,
+ font_size=40,
)
self.add(title, graphs, grid, grid_labels)
@@ -1477,7 +1478,7 @@ class NumberPlane(Axes):
"include_tip": False,
"line_to_number_buff": SMALL_BUFF,
"label_direction": DR,
- "number_scale_value": 0.5,
+ "font_size": 24,
}
self.y_axis_config = {"label_direction": DR}
self.background_line_style = {
@@ -1729,8 +1730,8 @@ class PolarPlane(Axes):
azimuth_label_buff
The buffer for the azimuth labels.
- azimuth_label_scale
- The scale of the azimuth labels.
+ azimuth_label_font_size
+ The font size of the azimuth labels.
radius_config
The axis config for the radius.
@@ -1747,12 +1748,18 @@ class PolarPlane(Axes):
polarplane_pi = PolarPlane(
azimuth_units="PI radians",
size=6,
- azimuth_label_scale=0.7,
- radius_config={"number_scale_value": 0.7},
+ azimuth_label_font_size=33.6,
+ radius_config={"font_size": 33.6},
).add_coordinates()
self.add(polarplane_pi)
"""
+ @deprecated_params(
+ params="azimuth_label_scale",
+ since="v0.10.0",
+ until="v0.11.0",
+ message="Use azimuth_label_font_size instead. To convert old scale factors to font size, multiply by 48.",
+ )
def __init__(
self,
radius_max: float = config["frame_y_radius"],
@@ -1764,7 +1771,7 @@ class PolarPlane(Axes):
azimuth_offset: float = 0,
azimuth_direction: str = "CCW",
azimuth_label_buff: float = SMALL_BUFF,
- azimuth_label_scale: float = 0.5,
+ azimuth_label_font_size: float = 24,
radius_config: Optional[dict] = None,
background_line_style: Optional[dict] = None,
faded_line_style: Optional[dict] = None,
@@ -1772,6 +1779,14 @@ class PolarPlane(Axes):
make_smooth_after_applying_functions: bool = True,
**kwargs,
):
+ # deprecation
+ azimuth_label_scale = kwargs.pop("azimuth_label_scale", None)
+ if azimuth_label_scale:
+ self.azimuth_label_font_size = (
+ azimuth_label_scale * DEFAULT_FONT_SIZE * 0.75
+ )
+ else:
+ self.azimuth_label_font_size = azimuth_label_font_size
# error catching
if azimuth_units in ["PI radians", "TAU radians", "degrees", "gradians", None]:
@@ -1794,7 +1809,7 @@ class PolarPlane(Axes):
"include_tip": False,
"line_to_number_buff": SMALL_BUFF,
"label_direction": DL,
- "number_scale_value": 0.5,
+ "font_size": 24,
}
self.background_line_style = {
@@ -1828,7 +1843,7 @@ class PolarPlane(Axes):
self.make_smooth_after_applying_functions = make_smooth_after_applying_functions
self.azimuth_offset = azimuth_offset
self.azimuth_label_buff = azimuth_label_buff
- self.azimuth_label_scale = azimuth_label_scale
+ # self.azimuth_label_font_size = azimuth_label_font_size <-uncomment when deprecation is done
self.azimuth_compact_fraction = azimuth_compact_fraction
# init
@@ -2047,9 +2062,9 @@ class PolarPlane(Axes):
]
if self.azimuth_units == "PI radians" or self.azimuth_units == "TAU radians":
a_tex = [
- self.get_radian_label(i["label"])
- .scale(self.azimuth_label_scale)
- .next_to(
+ self.get_radian_label(
+ i["label"], font_size=self.azimuth_label_font_size
+ ).next_to(
i["point"],
direction=i["point"],
aligned_edge=i["point"],
@@ -2059,9 +2074,10 @@ class PolarPlane(Axes):
]
elif self.azimuth_units == "degrees":
a_tex = [
- MathTex(f'{360 * i["label"]:g}' + r"^{\circ}")
- .scale(self.azimuth_label_scale)
- .next_to(
+ MathTex(
+ f'{360 * i["label"]:g}' + r"^{\circ}",
+ font_size=self.azimuth_label_font_size,
+ ).next_to(
i["point"],
direction=i["point"],
aligned_edge=i["point"],
@@ -2071,9 +2087,10 @@ class PolarPlane(Axes):
]
elif self.azimuth_units == "gradians":
a_tex = [
- MathTex(f'{400 * i["label"]:g}' + r"^{g}")
- .scale(self.azimuth_label_scale)
- .next_to(
+ MathTex(
+ f'{400 * i["label"]:g}' + r"^{g}",
+ font_size=self.azimuth_label_font_size,
+ ).next_to(
i["point"],
direction=i["point"],
aligned_edge=i["point"],
@@ -2083,9 +2100,9 @@ class PolarPlane(Axes):
]
elif self.azimuth_units is None:
a_tex = [
- MathTex(f'{i["label"]:g}')
- .scale(self.azimuth_label_scale)
- .next_to(
+ MathTex(
+ f'{i["label"]:g}', font_size=self.azimuth_label_font_size
+ ).next_to(
i["point"],
direction=i["point"],
aligned_edge=i["point"],
@@ -2113,30 +2130,29 @@ class PolarPlane(Axes):
self.add(self.get_coordinate_labels(r_values, a_values))
return self
- def get_radian_label(self, number, stacked=True):
+ def get_radian_label(self, number, font_size=24, **kwargs):
constant_label = {"PI radians": r"\pi", "TAU radians": r"\tau"}[
self.azimuth_units
]
division = number * {"PI radians": 2, "TAU radians": 1}[self.azimuth_units]
frac = fr.Fraction(division).limit_denominator(max_denominator=100)
if frac.numerator == 0 & frac.denominator == 0:
- return MathTex(r"0")
+ string = r"0"
elif frac.numerator == 1 and frac.denominator == 1:
- return MathTex(constant_label)
+ string = constant_label
elif frac.numerator == 1:
if self.azimuth_compact_fraction:
- return MathTex(
+ string = (
r"\tfrac{" + constant_label + r"}{" + str(frac.denominator) + "}"
)
else:
- return MathTex(
- r"\tfrac{1}{" + str(frac.denominator) + "}" + constant_label
- )
+ string = r"\tfrac{1}{" + str(frac.denominator) + "}" + constant_label
elif frac.denominator == 1:
- return MathTex(str(frac.numerator) + constant_label)
+ string = str(frac.numerator) + constant_label
+
else:
if self.azimuth_compact_fraction:
- return MathTex(
+ string = (
r"\tfrac{"
+ str(frac.numerator)
+ constant_label
@@ -2145,7 +2161,7 @@ class PolarPlane(Axes):
+ r"}"
)
else:
- return MathTex(
+ string = (
r"\tfrac{"
+ str(frac.numerator)
+ r"}{"
@@ -2154,6 +2170,8 @@ class PolarPlane(Axes):
+ constant_label
)
+ return MathTex(string, font_size=font_size, **kwargs)
+
class ComplexPlane(NumberPlane):
"""
diff --git a/manim/mobject/geometry.py b/manim/mobject/geometry.py
index b0390aa40..05ae64819 100644
--- a/manim/mobject/geometry.py
+++ b/manim/mobject/geometry.py
@@ -446,7 +446,7 @@ class ArcBetweenPoints(Arc):
arc_height = radius - math.sqrt(radius ** 2 - halfdist ** 2)
angle = math.acos((radius - arc_height) / radius) * sign
- Arc.__init__(self, radius=radius, angle=angle, **kwargs)
+ super().__init__(radius=radius, angle=angle, **kwargs)
if angle == 0:
self.set_points_as_corners([LEFT, RIGHT])
self.put_start_and_end_on(start, end)
@@ -506,8 +506,7 @@ class Circle(Arc):
color=RED,
**kwargs,
):
- Arc.__init__(
- self,
+ super().__init__(
radius=radius,
start_angle=0,
angle=TAU,
diff --git a/manim/mobject/number_line.py b/manim/mobject/number_line.py
index 798a524dd..fbe120721 100644
--- a/manim/mobject/number_line.py
+++ b/manim/mobject/number_line.py
@@ -2,9 +2,10 @@
__all__ = ["NumberLine", "UnitInterval"]
-from typing import TYPE_CHECKING, Dict, Union
+from typing import TYPE_CHECKING, Dict, Iterable, Optional, Sequence, Union
import numpy as np
+from colour import Color
from manim.mobject.svg.tex_mobject import MathTex, Tex
@@ -16,6 +17,7 @@ from ..mobject.types.vectorized_mobject import VGroup
from ..utils.bezier import interpolate
from ..utils.color import LIGHT_GREY
from ..utils.config_ops import merge_dicts_recursively
+from ..utils.deprecation import deprecated_params
from ..utils.simple_functions import fdiv
from ..utils.space_ops import normalize
@@ -30,46 +32,48 @@ class NumberLine(Line):
Parameters
----------
- x_range : Union[:class:`list`, :class:`numpy.ndarray`]
+ x_range
The :code:`[x_min, x_max, x_step]` values to create the line.
- length : :class:`float`
+ length
The length of the number line.
- unit_size : class:`float`
+ unit_size
The distance between each tick of the line. Overwritten by :attr:`length`, if specified.
- include_ticks : :class:`bool`
- Determines whether ticks are included.
- tick_size : :class:`float`
- The vertical length of each tick mark.
- numbers_with_elongated_ticks : Union[:class:`list`, :class:`numpy.ndarray`]
- A list of specific values with elongated ticks.
- longer_tick_multiple : :class:`float`
+ include_ticks
+ Whether to include ticks on the number line.
+ tick_size
+ The length of each tick mark.
+ numbers_with_elongated_ticks
+ An iterable of specific values with elongated ticks.
+ longer_tick_multiple
Influences how many times larger elongated ticks are than regular ticks (2 = 2x).
- color : :class:`~.Colors`
+ color
The color of the line.
- rotation : :class:`float`
+ rotation
The angle (in radians) at which the line is rotated.
- stroke_width : :class:`float`
+ stroke_width
The thickness of the line.
- include_tip : :class:`bool`
- Determines whether a tip is added to the end of the line.
- tip_width : :class:`float`
+ include_tip
+ Whether to add a tip to the end of the line.
+ tip_width
The width of the tip.
- tip_height : :class:`float`
+ tip_height
The height of the tip.
- include_numbers : :class:`bool`
- Determines whether numbers are added to tick marks. The number of decimal places is determined
+ include_numbers
+ Whether to add numbers to the tick marks. The number of decimal places is determined
by the step size, this default can be overridden by ``decimal_number_config``.
- label_direction : Union[:class:`list`, :class:`numpy.ndarray`]
- The specific position to which number mobjects are added on the line.
- line_to_number_buff : :class:`float`
- The distance between the line and the number mobject.
- decimal_number_config : :class:`dict`
+ font size
+ The size of the label mobjects. Defaults to 36.
+ label_direction
+ The specific position to which label mobjects are added on the line.
+ line_to_number_buff
+ The distance between the line and the label mobject.
+ decimal_number_config
Arguments that can be passed to :class:`~.numbers.DecimalNumber` to influence number mobjects.
- numbers_to_exclude : Union[:class:`list`, :class:`numpy.ndarray`]
- An explicit list of numbers to not be added to the line.
- number_scale_value : :class:`float`
- The size scaling factor for the number mobjects.
- kwargs : Any
+ numbers_to_exclude
+ An explicit iterable of numbers to not be added to the number line.
+ numbers_to_include
+ An explicit iterable of numbers to add to the number line
+ kwargs
Additional arguments to be passed to :class:`~.Line`.
Examples
@@ -92,7 +96,7 @@ class NumberLine(Line):
unit_size=0.5,
numbers_with_elongated_ticks=[-2, 4],
include_numbers=True,
- number_scale_value=0.5,
+ font_size=24,
)
[num6] = [num for num in l1.numbers if num.number == 6]
num6.set_color(RED)
@@ -122,36 +126,48 @@ class NumberLine(Line):
The constructed number line.
"""
+ @deprecated_params(
+ params="number_scale_value",
+ since="v0.10.0",
+ until="v0.11.0",
+ message="Use font_size instead. To convert old scale factors to font size, multiply by 48.",
+ )
def __init__(
self,
- x_range=None, # must be first
- length=None,
- unit_size=1,
+ x_range: Optional[Sequence[float]] = None, # must be first
+ length: Optional[float] = None,
+ unit_size: float = 1,
# ticks
- include_ticks=True,
- tick_size=0.1,
- numbers_with_elongated_ticks=None,
- longer_tick_multiple=2,
+ include_ticks: bool = True,
+ tick_size: float = 0.1,
+ numbers_with_elongated_ticks: Optional[Iterable[float]] = None,
+ longer_tick_multiple: int = 2,
+ exclude_origin_tick: bool = False,
# visuals
- color=LIGHT_GREY,
- rotation=0,
- stroke_width=2.0,
+ color: Color = LIGHT_GREY,
+ rotation: float = 0,
+ stroke_width: float = 2.0,
# tip
- include_tip=False,
- tip_width=0.25,
- tip_height=0.25,
+ include_tip: bool = False,
+ tip_width: float = 0.25,
+ tip_height: float = 0.25,
# numbers
- include_numbers=False,
- label_direction=DOWN,
- line_to_number_buff=MED_SMALL_BUFF,
- decimal_number_config=None,
- numbers_to_exclude=None,
- numbers_to_include=None,
- # temp, because DecimalNumber() needs to be updated
- number_scale_value=0.75,
- exclude_origin_tick=False,
- **kwargs
+ include_numbers: bool = False,
+ font_size: float = 36,
+ label_direction: Sequence[float] = DOWN,
+ line_to_number_buff: float = MED_SMALL_BUFF,
+ decimal_number_config: Optional[Dict] = None,
+ numbers_to_exclude: Optional[Iterable[float]] = None,
+ numbers_to_include: Optional[Iterable[float]] = None,
+ **kwargs,
):
+ # deprecation
+ number_scale_value = kwargs.pop("number_scale_value", None)
+ if number_scale_value is not None:
+ self.font_size = number_scale_value * DEFAULT_FONT_SIZE * 0.75
+ else:
+ self.font_size = font_size
+
# avoid mutable arguments in defaults
if numbers_to_exclude is None:
numbers_to_exclude = []
@@ -196,7 +212,6 @@ class NumberLine(Line):
self.decimal_number_config = decimal_number_config
self.numbers_to_exclude = numbers_to_exclude
self.numbers_to_include = numbers_to_include
- self.number_scale_value = number_scale_value
super().__init__(
self.x_min * RIGHT,
@@ -223,13 +238,17 @@ class NumberLine(Line):
self.rotate(self.rotation)
if self.include_numbers or self.numbers_to_include is not None:
self.add_numbers(
- x_values=self.numbers_to_include, excluding=self.numbers_to_exclude
+ x_values=self.numbers_to_include,
+ excluding=self.numbers_to_exclude,
+ font_size=self.font_size,
)
- def rotate_about_zero(self, angle, axis=OUT, **kwargs):
+ def rotate_about_zero(self, angle: float, axis: Sequence[float] = OUT, **kwargs):
return self.rotate_about_number(0, angle, axis, **kwargs)
- def rotate_about_number(self, number, angle, axis=OUT, **kwargs):
+ def rotate_about_number(
+ self, number: float, angle: float, axis: Sequence[float] = OUT, **kwargs
+ ):
return self.rotate(angle, axis, about_point=self.n2p(number), **kwargs)
def add_ticks(self):
@@ -243,7 +262,7 @@ class NumberLine(Line):
self.add(ticks)
self.ticks = ticks
- def get_tick(self, x, size=None):
+ def get_tick(self, x: float, size: Optional[float] = None) -> Line:
if size is None:
size = self.tick_size
result = Line(size * DOWN, size * UP)
@@ -252,10 +271,10 @@ class NumberLine(Line):
result.match_style(self)
return result
- def get_tick_marks(self):
+ def get_tick_marks(self) -> VGroup:
return VGroup(self.ticks)
- def get_tick_range(self):
+ def get_tick_range(self) -> np.ndarray:
if self.include_tip:
x_max = self.x_max
else:
@@ -276,11 +295,11 @@ class NumberLine(Line):
return np.unique(np.concatenate((x_min_segment, x_max_segment)))
- def number_to_point(self, number):
+ def number_to_point(self, number: float) -> np.ndarray:
alpha = float(number - self.x_min) / (self.x_max - self.x_min)
return interpolate(self.get_start(), self.get_end(), alpha)
- def point_to_number(self, point):
+ def point_to_number(self, point: Sequence[float]) -> float:
start, end = self.get_start_and_end()
unit_vect = normalize(end - start)
proportion = fdiv(
@@ -289,21 +308,28 @@ class NumberLine(Line):
)
return interpolate(self.x_min, self.x_max, proportion)
- def n2p(self, number):
+ def n2p(self, number: float) -> np.ndarray:
"""Abbreviation for number_to_point"""
return self.number_to_point(number)
- def p2n(self, point):
+ def p2n(self, point: Sequence[float]) -> float:
"""Abbreviation for point_to_number"""
return self.point_to_number(point)
- def get_unit_size(self):
+ def get_unit_size(self) -> float:
return self.get_length() / (self.x_max - self.x_min)
- def get_unit_vector(self):
+ def get_unit_vector(self) -> np.ndarray:
return super().get_unit_vector() * self.unit_size
- def get_number_mobject(self, x, direction=None, buff=None, **number_config):
+ def get_number_mobject(
+ self,
+ x: float,
+ direction: Optional[Sequence[float]] = None,
+ buff: Optional[float] = None,
+ font_size: Optional[float] = None,
+ **number_config,
+ ) -> DecimalNumber:
number_config = merge_dicts_recursively(
self.decimal_number_config, number_config
)
@@ -311,9 +337,10 @@ class NumberLine(Line):
direction = self.label_direction
if buff is None:
buff = self.line_to_number_buff
+ if font_size is None:
+ font_size = self.font_size
- num_mob = DecimalNumber(x, **number_config)
- num_mob.scale(self.number_scale_value)
+ num_mob = DecimalNumber(x, font_size=font_size, **number_config)
num_mob.next_to(self.number_to_point(x), direction=direction, buff=buff)
if x < 0 and self.label_direction[0] == 0:
@@ -321,21 +348,31 @@ class NumberLine(Line):
num_mob.shift(num_mob[0].get_width() * LEFT / 2)
return num_mob
- def get_number_mobjects(self, *numbers, **kwargs):
+ def get_number_mobjects(self, *numbers, **kwargs) -> VGroup:
if len(numbers) == 0:
numbers = self.default_numbers_to_display()
return VGroup([self.get_number_mobject(number, **kwargs) for number in numbers])
- def get_labels(self):
+ def get_labels(self) -> VGroup:
return self.get_number_mobjects()
- def add_numbers(self, x_values=None, excluding=None, **kwargs):
+ def add_numbers(
+ self,
+ x_values: Optional[Iterable[float]] = None,
+ excluding: Optional[Iterable[float]] = None,
+ font_size: Optional[float] = None,
+ **kwargs,
+ ) -> VGroup:
if x_values is None:
x_values = self.get_tick_range()
if excluding is None:
excluding = self.numbers_to_exclude
+ if font_size is None:
+ font_size = self.font_size
+ kwargs["font_size"] = font_size
+
numbers = VGroup()
for x in x_values:
if x in excluding:
@@ -350,18 +387,20 @@ class NumberLine(Line):
dict_values: Dict[float, Union[str, float, "Mobject"]],
direction=None,
buff=None,
+ font_size=None,
):
"""Adds specifically positioned labels to the :class:`~.NumberLine` using a ``dict``."""
- if direction is None:
- direction = self.label_direction
- if buff is None:
- buff = self.line_to_number_buff
+ direction = self.label_direction if direction is None else direction
+ buff = self.line_to_number_buff if buff is None else buff
+ font_size = self.font_size if font_size is None else font_size
labels = VGroup()
for x, label in dict_values.items():
-
+ if hasattr(label, "font_size"):
+ label.font_size = font_size
+ else:
+ raise AttributeError(f"{label} is not compatible with add_labels.")
label = self.create_label_tex(label)
- label.scale(self.number_scale_value)
label.next_to(self.number_to_point(x), direction=direction, buff=buff)
labels.add(label)
@@ -389,7 +428,7 @@ class NumberLine(Line):
label_tex = Tex(label_tex)
return label_tex
- def decimal_places_from_step(self):
+ def decimal_places_from_step(self) -> int:
step_as_str = str(self.x_step)
if "." not in step_as_str:
return 0
@@ -402,7 +441,7 @@ class UnitInterval(NumberLine):
unit_size=10,
numbers_with_elongated_ticks=None,
decimal_number_config=None,
- **kwargs
+ **kwargs,
):
numbers_with_elongated_ticks = (
[0, 1]
diff --git a/manim/mobject/numbers.py b/manim/mobject/numbers.py
index 2bafb5291..a4404bc87 100644
--- a/manim/mobject/numbers.py
+++ b/manim/mobject/numbers.py
@@ -2,17 +2,19 @@
__all__ = ["DecimalNumber", "Integer", "Variable"]
-import uuid
+from typing import Optional, Sequence
import numpy as np
+from .. import config
from ..constants import *
from ..mobject.svg.tex_mobject import MathTex, SingleStringMathTex
from ..mobject.types.vectorized_mobject import VMobject
from ..mobject.value_tracker import ValueTracker
-from ..utils.family import extract_mobject_family_members
from .opengl_compatibility import ConvertToOpenGL
+string_to_mob_map = {}
+
class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
"""An mobject representing a decimal number.
@@ -46,15 +48,18 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
def __init__(
self,
- number=0,
- num_decimal_places=2,
- include_sign=False,
- group_with_commas=True,
- digit_to_digit_buff=0.05,
- show_ellipsis=False,
- unit=None, # Aligned to bottom unless it starts with "^"
- include_background_rectangle=False,
- edge_to_fix=LEFT,
+ number: float = 0,
+ num_decimal_places: int = 2,
+ include_sign: bool = False,
+ group_with_commas: bool = True,
+ digit_buff_per_font_unit: float = 0.001,
+ show_ellipsis: bool = False,
+ unit: Optional[str] = None, # Aligned to bottom unless it starts with "^"
+ include_background_rectangle: bool = False,
+ edge_to_fix: Sequence[float] = LEFT,
+ font_size: float = DEFAULT_FONT_SIZE,
+ stroke_width: float = 0,
+ fill_opacity: float = 1.0,
**kwargs
):
super().__init__(**kwargs)
@@ -62,11 +67,14 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
self.num_decimal_places = num_decimal_places
self.include_sign = include_sign
self.group_with_commas = group_with_commas
- self.digit_to_digit_buff = digit_to_digit_buff
+ self.digit_buff_per_font_unit = digit_buff_per_font_unit
self.show_ellipsis = show_ellipsis
self.unit = unit
self.include_background_rectangle = include_background_rectangle
self.edge_to_fix = edge_to_fix
+ self._font_size = font_size
+ self.stroke_width = stroke_width
+ self.fill_opacity = fill_opacity
self.initial_config = kwargs.copy()
self.initial_config.update(
@@ -74,42 +82,58 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
"num_decimal_places": num_decimal_places,
"include_sign": include_sign,
"group_with_commas": group_with_commas,
- "digit_to_digit_buff": digit_to_digit_buff,
+ "digit_buff_per_font_unit": digit_buff_per_font_unit,
"show_ellipsis": show_ellipsis,
"unit": unit,
"include_background_rectangle": include_background_rectangle,
"edge_to_fix": edge_to_fix,
+ "font_size": font_size,
+ "stroke_width": stroke_width,
+ "fill_opacity": fill_opacity,
}
)
- if isinstance(number, complex):
- formatter = self.get_complex_formatter()
- else:
- formatter = self.get_formatter()
- num_string = formatter.format(number)
+ self.set_submobjects_from_number(number)
+ self.init_colors()
- rounded_num = np.round(number, self.num_decimal_places)
- if num_string.startswith("-") and rounded_num == 0:
- if self.include_sign:
- num_string = "+" + num_string[1:]
- else:
- num_string = num_string[1:]
+ @property
+ def font_size(self):
+ """The font size of the tex mobject."""
+ return self._font_size
+
+ @font_size.setter
+ def font_size(self, font_val):
+ if font_val <= 0:
+ raise ValueError("font_size must be greater than 0.")
+ elif self.height > 0:
+ # sometimes manim generates a SingleStringMathex mobject with 0 height.
+ # can't be scaled regardless and will error without the elif.
+
+ # scale to a factor of the initial height so that setting
+ # font_size does not depend on current size.
+ self.scale(1 / 48 * font_val * self.initial_height / self.height)
+ self._font_size = font_val
+
+ def set_submobjects_from_number(self, number):
+ self.number = number
+ self.set_submobjects([])
- self.add(*(SingleStringMathTex(char, **kwargs) for char in num_string))
+ num_string = self.get_num_string(number)
+ self.add(*(map(self.string_to_mob, num_string)))
# Add non-numerical bits
if self.show_ellipsis:
- self.add(SingleStringMathTex("\\dots", color=self.color))
-
- if num_string.startswith("-"):
- minus = self.submobjects[0]
- minus.next_to(self.submobjects[1], LEFT, buff=self.digit_to_digit_buff)
+ self.add(
+ self.string_to_mob("\\dots", SingleStringMathTex, color=self.color)
+ )
if self.unit is not None:
- self.unit_sign = SingleStringMathTex(self.unit, color=self.color)
+ self.unit_sign = self.string_to_mob(self.unit, SingleStringMathTex)
self.add(self.unit_sign)
- self.arrange(buff=self.digit_to_digit_buff, aligned_edge=DOWN)
+ self.arrange(
+ buff=self.digit_buff_per_font_unit * self._font_size, aligned_edge=DOWN
+ )
# Handle alignment of parts that should be aligned
# to the bottom
@@ -121,10 +145,36 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
self[i].shift(self[i].height * DOWN / 2)
if self.unit and self.unit.startswith("^"):
self.unit_sign.align_to(self, UP)
- #
+
if self.include_background_rectangle:
self.add_background_rectangle()
+ # track the initial height to enable scaling via font_size
+ self.initial_height = self.height
+
+ def get_num_string(self, number):
+ if isinstance(number, complex):
+ formatter = self.get_complex_formatter()
+ else:
+ formatter = self.get_formatter()
+ num_string = formatter.format(number)
+
+ rounded_num = np.round(number, self.num_decimal_places)
+ if num_string.startswith("-") and rounded_num == 0:
+ if self.include_sign:
+ num_string = "+" + num_string[1:]
+ else:
+ num_string = num_string[1:]
+
+ return num_string
+
+ def string_to_mob(self, string, mob_class=MathTex, **kwargs):
+ if string not in string_to_mob_map:
+ string_to_mob_map[string] = mob_class(string, font_size=1.0, **kwargs)
+ mob = string_to_mob_map[string].copy()
+ mob.font_size = self._font_size
+ return mob
+
def get_formatter(self, **kwargs):
"""
Configuration is based first off instance attributes,
@@ -158,7 +208,7 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
]
)
- def get_complex_formatter(self, **kwargs):
+ def get_complex_formatter(self):
return "".join(
[
self.get_formatter(field_name="0.real"),
@@ -167,35 +217,28 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
]
)
- def set_value(self, number, **config):
- full_config = {}
- full_config.update(self.initial_config)
- full_config.update(config)
- new_decimal = DecimalNumber(number, **full_config)
-
- if hasattr(self, "original_id"):
- if not hasattr(self, "generated_original_ids"):
- self.generated_original_ids = []
- new_submobjects = extract_mobject_family_members(
- new_decimal, only_those_with_points=True
- )
- while len(self.generated_original_ids) < len(new_submobjects):
- self.generated_original_ids.append(str(uuid.uuid4()))
- for new_submobject, generated_id in zip(
- new_submobjects, self.generated_original_ids
- ):
- new_submobject.original_id = generated_id
-
- # Make sure last digit has constant height
- new_decimal.scale(self[-1].height / new_decimal[-1].height)
- new_decimal.move_to(self, self.edge_to_fix)
- new_decimal.match_style(self)
+ def set_value(self, number):
old_family = self.get_family()
- self.set_submobjects(new_decimal.submobjects)
- for mobj in old_family:
- mobj.clear_points()
+ move_to_point = self.get_edge_center(self.edge_to_fix)
+ old_submobjects = self.submobjects
+ self.set_submobjects_from_number(number)
+ self.move_to(move_to_point, self.edge_to_fix)
+ for sm1, sm2 in zip(self.submobjects, old_submobjects):
+ sm1.match_style(sm2)
+
+ if config.renderer != "opengl":
+ for mob in old_family:
+ # Dumb hack...due to how scene handles families
+ # of animated mobjects
+ # for compatibility with updaters to not leave first number in place while updating,
+ # not needed with opengl renderer
+ mob.points[:] = 0
- self.number = number
+ return self
+
+ def scale(self, scale_factor, **kwargs):
+ super().scale(scale_factor, **kwargs)
+ self._font_size *= scale_factor
return self
def get_value(self):
@@ -223,9 +266,7 @@ class Integer(DecimalNumber):
"""
def __init__(self, number=0, num_decimal_places=0, **kwargs):
- DecimalNumber.__init__(
- self, number=number, num_decimal_places=num_decimal_places, **kwargs
- )
+ super().__init__(number=number, num_decimal_places=num_decimal_places, **kwargs)
def get_value(self):
return int(np.round(super().get_value()))
diff --git a/manim/mobject/svg/brace.py b/manim/mobject/svg/brace.py
index e030984b9..4f4e93b8e 100644
--- a/manim/mobject/svg/brace.py
+++ b/manim/mobject/svg/brace.py
@@ -18,6 +18,7 @@ from ...mobject.svg.svg_path import SVGPathMobject
from ...mobject.svg.tex_mobject import MathTex, Tex
from ...mobject.types.vectorized_mobject import VMobject
from ...utils.color import BLACK
+from ...utils.deprecation import deprecated_params
class Brace(SVGPathMobject):
@@ -147,18 +148,29 @@ class Brace(SVGPathMobject):
class BraceLabel(VMobject, metaclass=ConvertToOpenGL):
+ @deprecated_params(
+ params="label_scale",
+ since="v0.10.0",
+ until="v0.11.0",
+ message="Use font_size instead. To convert old scale factors to font size, multiply by 48.",
+ )
def __init__(
self,
obj,
text,
brace_direction=DOWN,
label_constructor=MathTex,
- label_scale=1,
+ font_size=DEFAULT_FONT_SIZE,
buff=0.2,
**kwargs
):
+ label_scale = kwargs.pop("label_scale", None)
+ if label_scale:
+ self.font_size = label_scale * DEFAULT_FONT_SIZE
+ else:
+ self.font_size = font_size
+
self.label_constructor = label_constructor
- self.label_scale = label_scale
super().__init__(**kwargs)
self.brace_direction = brace_direction
@@ -168,11 +180,9 @@ class BraceLabel(VMobject, metaclass=ConvertToOpenGL):
self.brace = Brace(obj, brace_direction, buff, **kwargs)
if isinstance(text, tuple) or isinstance(text, list):
- self.label = self.label_constructor(*text, **kwargs)
+ self.label = self.label_constructor(font_size=font_size, *text, **kwargs)
else:
- self.label = self.label_constructor(str(text))
- if self.label_scale != 1:
- self.label.scale(self.label_scale)
+ self.label = self.label_constructor(str(text), font_size=font_size)
self.brace.put_at_tip(self.label)
self.submobjects = [self.brace, self.label]
@@ -190,16 +200,14 @@ class BraceLabel(VMobject, metaclass=ConvertToOpenGL):
def change_label(self, *text, **kwargs):
self.label = self.label_constructor(*text, **kwargs)
- if self.label_scale != 1:
- self.label.scale(self.label_scale)
self.brace.put_at_tip(self.label)
self.submobjects[1] = self.label
return self
- def change_brace_label(self, obj, *text):
+ def change_brace_label(self, obj, *text, **kwargs):
self.shift_brace(obj)
- self.change_label(*text)
+ self.change_label(*text, **kwargs)
return self
diff --git a/manim/mobject/svg/code_mobject.py b/manim/mobject/svg/code_mobject.py
index 2d1885ea0..cb53f552a 100644
--- a/manim/mobject/svg/code_mobject.py
+++ b/manim/mobject/svg/code_mobject.py
@@ -20,6 +20,7 @@ from ...mobject.shape_matchers import SurroundingRectangle
from ...mobject.svg.text_mobject import Paragraph
from ...mobject.types.vectorized_mobject import VGroup
from ...utils.color import WHITE
+from ...utils.deprecation import deprecated_params
class Code(VGroup):
@@ -94,8 +95,8 @@ class Code(VGroup):
Number of space characters corresponding to a tab character. Defaults to 3.
line_spacing : :class:`float`, optional
Amount of space between lines in relation to font size. Defaults to 0.3, which means 30% of font size.
- scale_factor : class:`float`, optional
- A number which scales displayed code. Defaults to 0.5.
+ font_size : class:`float`, optional
+ A number which scales displayed code. Defaults to 24.
font : :class:`str`, optional
The name of the text font to be used. Defaults to ``"Monospac821 BT"``.
stroke_width : class:`float`, optional
@@ -148,13 +149,19 @@ class Code(VGroup):
styles_list = list(get_all_styles())
# For more information about pygments.styles visit https://pygments.org/docs/styles/
+ @deprecated_params(
+ params="scale_factor",
+ since="v0.10.0",
+ until="v0.11.0",
+ message="Use font_size instead. To convert old scale factors to font size, multiply by 48.",
+ )
def __init__(
self,
file_name=None,
code=None,
tab_width=3,
line_spacing=0.3,
- scale_factor=0.5,
+ font_size=24,
font="Monospac821 BT",
stroke_width=0,
margin=0.3,
@@ -175,11 +182,17 @@ class Code(VGroup):
stroke_width=stroke_width,
**kwargs,
)
+ # deprecation handling
+ scale_factor = kwargs.pop("scale_factor", None)
+ if scale_factor:
+ self.font_size = DEFAULT_FONT_SIZE / 2 * scale_factor
+ else:
+ self.font_size = font_size
+
self.background_stroke_color = background_stroke_color
self.background_stroke_width = background_stroke_width
self.tab_width = tab_width
self.line_spacing = line_spacing
- self.scale_factor = scale_factor
self.font = font
self.margin = margin
self.indentation_chars = indentation_chars
@@ -230,7 +243,7 @@ class Code(VGroup):
fill_opacity=1,
)
rect.round_corners(self.corner_radius)
- self.background_mobject = VGroup(rect)
+ self.background_mobject = rect
else:
if self.insert_line_no:
foreground = VGroup(self.code, self.line_numbers)
@@ -310,10 +323,11 @@ class Code(VGroup):
*list(line_numbers_array),
line_spacing=self.line_spacing,
alignment="right",
+ font_size=self.font_size,
font=self.font,
disable_ligatures=True,
stroke_width=self.stroke_width,
- ).scale(self.scale_factor)
+ )
for i in line_numbers:
i.set_color(self.default_color)
return line_numbers
@@ -336,10 +350,11 @@ class Code(VGroup):
*list(lines_text),
line_spacing=self.line_spacing,
tab_width=self.tab_width,
+ font_size=self.font_size,
font=self.font,
disable_ligatures=True,
stroke_width=self.stroke_width,
- ).scale(self.scale_factor)
+ )
for line_no in range(code.__len__()):
line = code.chars[line_no]
line_char_index = self.tab_spaces[line_no]
diff --git a/manim/mobject/svg/tex_mobject.py b/manim/mobject/svg/tex_mobject.py
index e0cc70fdd..7da68193d 100644
--- a/manim/mobject/svg/tex_mobject.py
+++ b/manim/mobject/svg/tex_mobject.py
@@ -35,11 +35,14 @@ from ...mobject.svg.svg_mobject import SVGMobject
from ...mobject.svg.svg_path import SVGPathMobject
from ...mobject.types.vectorized_mobject import VectorizedPoint, VGroup
from ...utils.color import BLACK, WHITE
+from ...utils.deprecation import deprecated_params
from ...utils.tex import TexTemplate
from ...utils.tex_file_writing import tex_to_svg_file
from .style_utils import parse_style
-TEX_MOB_SCALE_FACTOR = 0.05
+SCALE_FACTOR_PER_FONT_POINT = 1 / 960
+
+tex_string_to_mob_map = {}
class TexSymbol(SVGPathMobject):
@@ -71,9 +74,12 @@ class SingleStringMathTex(SVGMobject):
organize_left_to_right=False,
tex_environment="align*",
tex_template=None,
+ font_size=DEFAULT_FONT_SIZE,
color=Color(WHITE),
**kwargs,
):
+
+ self._font_size = font_size
self.organize_left_to_right = organize_left_to_right
self.tex_environment = tex_environment
if tex_template is None:
@@ -87,8 +93,7 @@ class SingleStringMathTex(SVGMobject):
environment=self.tex_environment,
tex_template=self.tex_template,
)
- SVGMobject.__init__(
- self,
+ super().__init__(
file_name=file_name,
should_center=should_center,
stroke_width=stroke_width,
@@ -101,14 +106,41 @@ class SingleStringMathTex(SVGMobject):
color=color,
**kwargs,
)
+ # used for scaling via font_size.setter
+ self.initial_height = self.height
+
if height is None:
- self.scale(TEX_MOB_SCALE_FACTOR)
+ self.font_size = self._font_size
+
if self.organize_left_to_right:
self.organize_submobjects_left_to_right()
def __repr__(self):
return f"{type(self).__name__}({repr(self.tex_string)})"
+ @property
+ def font_size(self):
+ """The font size of the tex mobject."""
+ return self._font_size
+
+ @font_size.setter
+ def font_size(self, font_val):
+ if font_val <= 0:
+ raise ValueError("font_size must be greater than 0.")
+ elif self.height > 0:
+ # sometimes manim generates a SingleStringMathex mobject with 0 height.
+ # can't be scaled regardless and will error without the elif.
+
+ # scale to a factor of the initial height so that setting
+ # font_size does not depend on current size.
+ self.scale(
+ SCALE_FACTOR_PER_FONT_POINT
+ * font_val
+ * self.initial_height
+ / self.height
+ )
+ self._font_size = font_val
+
def get_modified_expression(self, tex_string):
result = tex_string
result = result.strip()
@@ -255,8 +287,7 @@ class MathTex(SingleStringMathTex):
self.brace_notation_split_occurred = False
self.tex_strings = self.break_up_tex_strings(tex_strings)
try:
- SingleStringMathTex.__init__(
- self,
+ super().__init__(
self.arg_separator.join(self.tex_strings),
tex_environment=self.tex_environment,
tex_template=self.tex_template,
@@ -407,8 +438,7 @@ class Tex(MathTex):
def __init__(
self, *tex_strings, arg_separator="", tex_environment="center", **kwargs
):
- MathTex.__init__(
- self,
+ super().__init__(
*tex_strings,
arg_separator=arg_separator,
tex_environment=tex_environment,
@@ -445,8 +475,8 @@ class BulletedList(Tex):
self.dot_scale_factor = dot_scale_factor
self.tex_environment = tex_environment
line_separated_items = [s + "\\\\" for s in items]
- Tex.__init__(
- self, *line_separated_items, tex_environment=tex_environment, **kwargs
+ super().__init__(
+ *line_separated_items, tex_environment=tex_environment, **kwargs
)
for part in self:
dot = MathTex("\\cdot").scale(self.dot_scale_factor)
@@ -486,21 +516,28 @@ class Title(Tex):
"""
+ @deprecated_params(
+ params="scale_factor",
+ since="v0.10.0",
+ until="v0.11.0",
+ message="Use font_size instead. To convert old scale factors to font size, multiply by 48.",
+ )
def __init__(
self,
*text_parts,
- scale_factor=1,
include_underline=True,
match_underline_width_to_text=False,
underline_buff=MED_SMALL_BUFF,
**kwargs,
):
- self.scale_factor = scale_factor
+ scale_factor = kwargs.pop("scale_factor", None)
+ if scale_factor:
+ kwargs["font_size"] = DEFAULT_FONT_SIZE * scale_factor
+
self.include_underline = include_underline
self.match_underline_width_to_text = match_underline_width_to_text
self.underline_buff = underline_buff
- Tex.__init__(self, *text_parts, **kwargs)
- self.scale(self.scale_factor)
+ super().__init__(*text_parts, **kwargs)
self.to_edge(UP)
if self.include_underline:
underline_width = config["frame_width"] - 2
diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.py
index ae7cb196e..504b0764c 100644
--- a/manim/mobject/svg/text_mobject.py
+++ b/manim/mobject/svg/text_mobject.py
@@ -60,6 +60,7 @@ from typing import Dict, Union
import manimpango
import numpy as np
+from colour import Color
from manimpango import MarkupUtils, PangoUtils, TextSetting
from ... import config, logger
@@ -68,12 +69,15 @@ from ...mobject.geometry import Dot
from ...mobject.svg.svg_mobject import SVGMobject
from ...mobject.types.vectorized_mobject import VGroup
from ...utils.color import WHITE, Colors
+from ...utils.deprecation import deprecated_params
TEXT_MOB_SCALE_FACTOR = 0.05
+DEFAULT_LINE_SPACING_SCALE = 0.3
+TEXT2SVG_ADJUSTMENT_FACTOR = 4.8
def remove_invisible_chars(mobject):
- """Function to remove unwanted invisible characters from some mobject
+ """Function to remove unwanted invisible characters from some mobjects.
Parameters
----------
@@ -140,7 +144,7 @@ class Paragraph(VGroup):
def __init__(self, *text, line_spacing=-1, alignment=None, **config):
self.line_spacing = line_spacing
self.alignment = alignment
- VGroup.__init__(self)
+ super().__init__()
lines_str = "\n".join(list(text))
self.lines_text = Text(lines_str, line_spacing=line_spacing, **config)
@@ -394,13 +398,19 @@ class Text(SVGMobject):
"""
+ @deprecated_params(
+ params="size",
+ since="v0.10.0",
+ until="v0.11.0",
+ message="Use font_size instead. To convert old scale factors to font size, multiply by 48.",
+ )
def __init__(
self,
text: str,
fill_opacity: float = 1.0,
- stroke_width: int = 0,
- color: str = WHITE,
- size: int = 1,
+ stroke_width: float = 0,
+ color: Color = WHITE,
+ font_size: float = DEFAULT_FONT_SIZE,
line_spacing: int = -1,
font: str = "",
slant: str = NORMAL,
@@ -420,7 +430,14 @@ class Text(SVGMobject):
disable_ligatures: bool = False,
**kwargs,
):
- self.size = size
+ # deprecation
+ size = kwargs.pop("size", None)
+ if size is not None:
+ self._font_size = size * DEFAULT_FONT_SIZE
+ else:
+ # needs to be a float or else size is inflated when font_size = 24 (unknown cause)
+ self._font_size = float(font_size)
+
self.line_spacing = line_spacing
self.font = font
self.slant = slant
@@ -456,13 +473,14 @@ class Text(SVGMobject):
text_without_tabs = text.replace("\t", " " * self.tab_width)
self.text = text_without_tabs
if self.line_spacing == -1:
- self.line_spacing = self.size + self.size * 0.3
+ self.line_spacing = (
+ self._font_size + self._font_size * DEFAULT_LINE_SPACING_SCALE
+ )
else:
- self.line_spacing = self.size + self.size * self.line_spacing
+ self.line_spacing = self._font_size + self._font_size * self.line_spacing
file_name = self.text2svg()
PangoUtils.remove_last_M(file_name)
- SVGMobject.__init__(
- self,
+ super().__init__(
file_name,
color=color,
fill_opacity=fill_opacity,
@@ -510,10 +528,29 @@ class Text(SVGMobject):
# anti-aliasing
if height is None and width is None:
self.scale(TEXT_MOB_SCALE_FACTOR)
+ self.initial_height = self.height
def __repr__(self):
return f"Text({repr(self.original_text)})"
+ @property
+ def font_size(self):
+ return self._font_size
+
+ @font_size.setter
+ def font_size(self, font_val):
+ if font_val <= 0:
+ raise ValueError("font_size must be greater than 0.")
+ else:
+ # multiply by (1/2.4) because it makes it work.
+ self.scale(
+ TEXT_MOB_SCALE_FACTOR
+ * (1 / 2.4)
+ * font_val
+ * self.initial_height
+ / self.height
+ )
+
def gen_chars(self):
chars = self.get_group_class()()
submobjects_char_index = 0
@@ -590,7 +627,7 @@ class Text(SVGMobject):
"PANGO" + self.font + self.slant + self.weight
) # to differentiate Text and CairoText
settings += str(self.t2f) + str(self.t2s) + str(self.t2w)
- settings += str(self.line_spacing) + str(self.size)
+ settings += str(self.line_spacing) + str(self._font_size)
settings += str(self.disable_ligatures)
id_str = self.text + settings
hasher = hashlib.sha256()
@@ -643,35 +680,39 @@ class Text(SVGMobject):
return settings
def text2svg(self):
- """Internally used function.
- Convert the text to SVG using Pango
- """
- size = self.size * 10
- line_spacing = self.line_spacing * 10
+ """Convert the text to SVG using Pango."""
+ size = self._font_size
+ line_spacing = self.line_spacing
+ size /= TEXT2SVG_ADJUSTMENT_FACTOR
+ line_spacing /= TEXT2SVG_ADJUSTMENT_FACTOR
+
dir_name = config.get_dir("text_dir")
- disable_liga = self.disable_ligatures
if not os.path.exists(dir_name):
os.makedirs(dir_name)
hash_name = self.text2hash()
file_name = os.path.join(dir_name, hash_name) + ".svg"
+
if os.path.exists(file_name):
- return file_name
- settings = self.text2settings()
- width = 600
- height = 400
-
- return manimpango.text2svg(
- settings,
- size,
- line_spacing,
- disable_liga,
- file_name,
- START_X,
- START_Y,
- width,
- height,
- self.text,
- )
+ svg_file = file_name
+ else:
+ settings = self.text2settings()
+ width = config["pixel_width"]
+ height = config["pixel_height"]
+
+ svg_file = manimpango.text2svg(
+ settings,
+ size,
+ line_spacing,
+ self.disable_ligatures,
+ file_name,
+ START_X,
+ START_Y,
+ width,
+ height,
+ self.text,
+ )
+
+ return svg_file
def init_colors(self, propagate_colors=True):
super().init_colors(propagate_colors=propagate_colors)
@@ -797,7 +838,7 @@ class MarkupText(SVGMobject):
Stroke width.
color : :class:`str`
Global color setting for the entire text. Local overrides are possible.
- size : :class:`int`
+ font_size : :class:`float`
Font size.
line_spacing : :class:`int`
Line spacing.
@@ -983,13 +1024,19 @@ class MarkupText(SVGMobject):
"""
+ @deprecated_params(
+ params="size",
+ since="v0.10.0",
+ until="v0.11.0",
+ message="Use font_size instead. To convert old scale factors to font size, multiply by 48.",
+ )
def __init__(
self,
text: str,
- fill_opacity: int = 1,
- stroke_width: int = 0,
- color: str = WHITE,
- size: int = 1,
+ fill_opacity: float = 1,
+ stroke_width: float = 0,
+ color: Color = WHITE,
+ font_size: float = DEFAULT_FONT_SIZE,
line_spacing: int = -1,
font: str = "",
slant: str = NORMAL,
@@ -1006,7 +1053,13 @@ class MarkupText(SVGMobject):
):
self.text = text
self.color = color
- self.size = size
+ # deprecation
+ size = kwargs.pop("size", None)
+ if size is not None:
+ self._font_size = size * DEFAULT_FONT_SIZE
+ else:
+ self._font_size = float(font_size)
+
self.line_spacing = line_spacing
self.font = font
self.slant = slant
@@ -1032,9 +1085,11 @@ class MarkupText(SVGMobject):
raise ValueError(validate_error)
if self.line_spacing == -1:
- self.line_spacing = self.size + self.size * 0.3
+ self.line_spacing = (
+ self._font_size + self._font_size * DEFAULT_LINE_SPACING_SCALE
+ )
else:
- self.line_spacing = self.size + self.size * self.line_spacing
+ self.line_spacing = self._font_size + self._font_size * self.line_spacing
file_name = self.text2svg()
PangoUtils.remove_last_M(file_name)
@@ -1094,12 +1149,32 @@ class MarkupText(SVGMobject):
if height is None and width is None:
self.scale(TEXT_MOB_SCALE_FACTOR)
+ self.initial_height = self.height
+
+ @property
+ def font_size(self):
+ return self._font_size
+
+ @font_size.setter
+ def font_size(self, font_val):
+ # TODO: use pango's font size scaling.
+ if font_val <= 0:
+ raise ValueError("font_size must be greater than 0.")
+ else:
+ self.scale(
+ TEXT_MOB_SCALE_FACTOR
+ * (1 / 2.4)
+ * font_val
+ * self.initial_height
+ / self.height
+ )
+
def text2hash(self):
"""Generates ``sha256`` hash for file name."""
settings = (
"MARKUPPANGO" + self.font + self.slant + self.weight + self.color
) # to differentiate from classical Pango Text
- settings += str(self.line_spacing) + str(self.size)
+ settings += str(self.line_spacing) + str(self._font_size)
settings += str(self.disable_ligatures)
settings += str(self.justify)
id_str = self.text + settings
@@ -1109,34 +1184,37 @@ class MarkupText(SVGMobject):
def text2svg(self):
"""Convert the text to SVG using Pango."""
- size = self.size * 10
- line_spacing = self.line_spacing * 10
+ size = self._font_size
+ line_spacing = self.line_spacing
+ size /= TEXT2SVG_ADJUSTMENT_FACTOR
+ line_spacing /= TEXT2SVG_ADJUSTMENT_FACTOR
+
dir_name = config.get_dir("text_dir")
- disable_liga = self.disable_ligatures
if not os.path.exists(dir_name):
os.makedirs(dir_name)
hash_name = self.text2hash()
file_name = os.path.join(dir_name, hash_name) + ".svg"
if os.path.exists(file_name):
- return file_name
-
- logger.debug(f"Setting Text {self.text}")
- return MarkupUtils.text2svg(
- f'<span foreground="{self.color}">{self.text}</span>',
- self.font,
- self.slant,
- self.weight,
- size,
- line_spacing,
- disable_liga,
- file_name,
- START_X,
- START_Y,
- 600, # width
- 400, # height
- justify=self.justify,
- pango_width=500,
- )
+ svg_file = file_name
+ else:
+ logger.debug(f"Setting Text {self.text}")
+ svg_file = MarkupUtils.text2svg(
+ f'<span foreground="{self.color}">{self.text}</span>',
+ self.font,
+ self.slant,
+ self.weight,
+ size,
+ line_spacing,
+ self.disable_ligatures,
+ file_name,
+ START_X,
+ START_Y,
+ 600, # width
+ 400, # height
+ justify=self.justify,
+ pango_width=500,
+ )
+ return svg_file
def _count_real_chars(self, s):
"""Counts characters that will be displayed.
diff --git a/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz b/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz
index 2653e3ccf..3ca51a4ad 100644
Binary files a/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz and b/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz differ
diff --git a/tests/control_data/graphical_units_data/coordinate_systems/NumberPlaneTest.npz b/tests/control_data/graphical_units_data/coordinate_systems/NumberPlaneTest.npz
new file mode 100644
index 000000000..3ed9e7b2d
Binary files /dev/null and b/tests/control_data/graphical_units_data/coordinate_systems/NumberPlaneTest.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/PlotFunctions.npz b/tests/control_data/graphical_units_data/plot/PlotFunctions.npz
new file mode 100644
index 000000000..7859d5d39
Binary files /dev/null and b/tests/control_data/graphical_units_data/plot/PlotFunctions.npz differ
diff --git a/tests/control_data/graphical_units_data/tables/DecimalTable.npz b/tests/control_data/graphical_units_data/tables/DecimalTable.npz
index 98f24dbae..d286f69fc 100644
Binary files a/tests/control_data/graphical_units_data/tables/DecimalTable.npz and b/tests/control_data/graphical_units_data/tables/DecimalTable.npz differ
diff --git a/tests/control_data/graphical_units_data/tables/IntegerTable.npz b/tests/control_data/graphical_units_data/tables/IntegerTable.npz
index 92199b68f..4b48a4cb1 100644
Binary files a/tests/control_data/graphical_units_data/tables/IntegerTable.npz and b/tests/control_data/graphical_units_data/tables/IntegerTable.npz differ
diff --git a/tests/test_texmobject.py b/tests/test_texmobject.py
index c9d7d1b2e..1524d8dcd 100644
--- a/tests/test_texmobject.py
+++ b/tests/test_texmobject.py
@@ -72,3 +72,12 @@ def test_tex_white_space_and_non_whitespace_args():
assert len(tex[1]) == len("".join((str_part_2 + separator).split()))
assert len(tex[2]) == len("".join((str_part_3 + separator).split()))
assert len(tex[3]) == len("".join(str_part_4.split()))
+
+
+def test_tex_size():
+ """Check that the size of a :class:`Tex` string is not changed."""
+ text = Tex("what").center()
+ vertical = text.get_top() - text.get_bottom()
+ horizontal = text.get_right() - text.get_left()
+ assert round(vertical[1], 4) == 0.3512
+ assert round(horizontal[0], 4) == 1.0420