Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add `label_constructor` parameter for :class:`~NumberLine`. (#2397)

Laith Bahodi7399c24b3309
diff --git a/manim/mobject/coordinate_systems.py b/manim/mobject/coordinate_systems.py
index aafb718fc..ec372bf44 100644
--- a/manim/mobject/coordinate_systems.py
+++ b/manim/mobject/coordinate_systems.py
@@ -339,25 +339,6 @@ class CoordinateSystem:
label, self.get_y_axis(), edge, direction, buff=buff, **kwargs
)
- # move to a util_file, or Mobject()??
- @staticmethod
- def _create_label_tex(label_tex) -> "Mobject":
- """Checks if the label is a ``float``, ``int`` or a ``str`` and creates a :class:`~.MathTex` label accordingly.
-
- Parameters
- ----------
- label_tex : The label to be compared against the above types.
-
- Returns
- -------
- :class:`~.Mobject`
- The label.
- """
-
- if isinstance(label_tex, (float, int, str)):
- label_tex = MathTex(label_tex)
- return label_tex
-
def _get_axis_label(
self,
label: Union[float, str, "Mobject"],
@@ -387,7 +368,7 @@ class CoordinateSystem:
The positioned label along the given axis.
"""
- label = self._create_label_tex(label)
+ label = self.x_axis._create_label_tex(label)
label.next_to(axis.get_edge_center(edge), direction=direction, buff=buff)
label.shift_onto_screen(buff=MED_SMALL_BUFF)
return label
@@ -997,7 +978,7 @@ class CoordinateSystem:
if dot_config is None:
dot_config = {}
- label = self._create_label_tex(label)
+ label = self.x_axis._create_label_tex(label)
color = color or graph.get_color()
label.set_color(color)
@@ -1550,11 +1531,11 @@ class CoordinateSystem:
labels = VGroup()
if dx_label is not None:
- group.dx_label = self._create_label_tex(dx_label)
+ group.dx_label = self.x_axis._create_label_tex(dx_label)
labels.add(group.dx_label)
group.add(group.dx_label)
if dy_label is not None:
- group.df_label = self._create_label_tex(dy_label)
+ group.df_label = self.x_axis._create_label_tex(dy_label)
labels.add(group.df_label)
group.add(group.df_label)
@@ -1710,7 +1691,7 @@ class CoordinateSystem:
triangle.height = triangle_size
triangle.move_to(self.coords_to_point(x_val, 0), UP)
if label is not None:
- t_label = self._create_label_tex(label).set_color(label_color)
+ t_label = self.x_axis._create_label_tex(label).set_color(label_color)
t_label.next_to(triangle, DOWN)
T_label_group.add(t_label)
diff --git a/manim/mobject/number_line.py b/manim/mobject/number_line.py
index 1e6b5aea0..754c8c542 100644
--- a/manim/mobject/number_line.py
+++ b/manim/mobject/number_line.py
@@ -2,10 +2,9 @@
__all__ = ["NumberLine", "UnitInterval"]
-from typing import TYPE_CHECKING, Dict, Iterable, Optional, Sequence, Union
+from typing import Dict, Iterable, Optional, Sequence, Union
import numpy as np
-from colour import Color
from manim.mobject.svg.tex_mobject import MathTex, Tex
from manim.utils.scale import LinearBase, _ScaleBase
@@ -14,15 +13,12 @@ from .. import config
from ..constants import *
from ..mobject.geometry import Line
from ..mobject.numbers import DecimalNumber
-from ..mobject.types.vectorized_mobject import VGroup
+from ..mobject.types.vectorized_mobject import VGroup, VMobject
from ..utils.bezier import interpolate
from ..utils.config_ops import merge_dicts_recursively
from ..utils.simple_functions import fdiv
from ..utils.space_ops import normalize
-if TYPE_CHECKING:
- from manim.mobject.mobject import Mobject
-
class NumberLine(Line):
"""Creates a number line with tick marks.
@@ -62,6 +58,8 @@ class NumberLine(Line):
The size of the label mobjects. Defaults to 36.
label_direction
The specific position to which label mobjects are added on the line.
+ label_constructor
+ Determines the mobject class that will be used to construct the labels of the number line.
line_to_number_buff
The distance between the line and the label mobject.
decimal_number_config
@@ -141,10 +139,11 @@ class NumberLine(Line):
include_tip: bool = False,
tip_width: float = 0.25,
tip_height: float = 0.25,
- # numbers
+ # numbers/labels
include_numbers: bool = False,
font_size: float = 36,
label_direction: Sequence[float] = DOWN,
+ label_constructor: VMobject = MathTex,
scaling: _ScaleBase = LinearBase(),
line_to_number_buff: float = MED_SMALL_BUFF,
decimal_number_config: Optional[Dict] = None,
@@ -194,6 +193,7 @@ class NumberLine(Line):
self.font_size = font_size
self.include_numbers = include_numbers
self.label_direction = label_direction
+ self.label_constructor = label_constructor
self.line_to_number_buff = line_to_number_buff
self.decimal_number_config = decimal_number_config
self.numbers_to_exclude = numbers_to_exclude
@@ -384,20 +384,26 @@ class NumberLine(Line):
direction: Optional[Sequence[float]] = None,
buff: Optional[float] = None,
font_size: Optional[float] = None,
+ label_constructor: Optional[VMobject] = None,
**number_config,
- ) -> DecimalNumber:
- """Generates a positioned :class:`~.DecimalNumber` mobject representing a number label.
+ ) -> VMobject:
+ """Generates a positioned :class:`~.DecimalNumber` mobject
+ generated according to ``label_constructor``.
Parameters
----------
x
- The x-value at which the tick should be positioned.
+ The x-value at which the mobject should be positioned.
direction
Determines the direction at which the label is positioned next to the line.
buff
The distance of the label from the line.
font_size
- The font size of the :class:`~.DecimalNumber` mobject.
+ The font size of the label mobject.
+ label_constructor
+ The :class:`~.VMobject` class that will be used to construct the label.
+ Defaults to the ``label_constructor`` attribute of the number line
+ if not specified.
Returns
-------
@@ -414,8 +420,12 @@ class NumberLine(Line):
buff = self.line_to_number_buff
if font_size is None:
font_size = self.font_size
+ if label_constructor is None:
+ label_constructor = self.label_constructor
- num_mob = DecimalNumber(x, font_size=font_size, **number_config)
+ num_mob = DecimalNumber(
+ x, font_size=font_size, mob_class=label_constructor, **number_config
+ )
num_mob.next_to(self.number_to_point(x), direction=direction, buff=buff)
if x < 0 and self.label_direction[0] == 0:
@@ -436,6 +446,7 @@ class NumberLine(Line):
x_values: Optional[Iterable[float]] = None,
excluding: Optional[Iterable[float]] = None,
font_size: Optional[float] = None,
+ label_constructor: Optional[VMobject] = None,
**kwargs,
):
"""Adds :class:`~.DecimalNumber` mobjects representing their position
@@ -452,6 +463,10 @@ class NumberLine(Line):
font_size
The font size of the labels. Defaults to the ``font_size`` attribute
of the number line.
+ label_constructor
+ The :class:`~.VMobject` class that will be used to construct the label.
+ Defaults to the ``label_constructor`` attribute of the number line
+ if not specified.
"""
if x_values is None:
@@ -462,23 +477,33 @@ class NumberLine(Line):
if font_size is None:
font_size = self.font_size
- kwargs["font_size"] = font_size
+
+ if label_constructor is None:
+ label_constructor = self.label_constructor
numbers = VGroup()
for x in x_values:
if x in excluding:
continue
- numbers.add(self.get_number_mobject(x, **kwargs))
+ numbers.add(
+ self.get_number_mobject(
+ x,
+ font_size=font_size,
+ label_constructor=label_constructor,
+ **kwargs,
+ )
+ )
self.add(numbers)
self.numbers = numbers
return self
def add_labels(
self,
- dict_values: Dict[float, Union[str, float, "Mobject"]],
+ dict_values: Dict[float, Union[str, float, VMobject]],
direction: Sequence[float] = None,
- buff: float = None,
- font_size: float = None,
+ buff: Optional[float] = None,
+ font_size: Optional[float] = None,
+ label_constructor: Optional[VMobject] = None,
):
"""Adds specifically positioned labels to the :class:`~.NumberLine` using a ``dict``.
The labels can be accessed after creation via ``self.labels``.
@@ -487,26 +512,43 @@ class NumberLine(Line):
----------
dict_values
A dictionary consisting of the position along the number line and the mobject to be added:
- ``{1: Tex("Monday"), 3: Tex("Tuesday")}``.
+ ``{1: Tex("Monday"), 3: Tex("Tuesday")}``. :attr:`label_constructor` will be used
+ to construct the labels if the value is not a mobject (``str`` or ``float``).
direction
Determines the direction at which the label is positioned next to the line.
buff
The distance of the label from the line.
font_size
The font size of the mobject to be positioned.
+ label_constructor
+ The :class:`~.VMobject` class that will be used to construct the label.
+ Defaults to the ``label_constructor`` attribute of the number line
+ if not specified.
Raises
------
AttributeError
If the label does not have a ``font_size`` attribute, an ``AttributeError`` is raised.
"""
+
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
+ label_constructor = (
+ self.label_constructor if label_constructor is None else label_constructor
+ )
labels = VGroup()
for x, label in dict_values.items():
- label = self._create_label_tex(label)
+
+ # TODO: remove this check and ability to call
+ # this method via CoordinateSystem.add_coordinates()
+ # must be explicitly called
+ if isinstance(label, str) and self.label_constructor is MathTex:
+ label = Tex(label)
+ else:
+ label = self._create_label_tex(label)
+
if hasattr(label, "font_size"):
label.font_size = font_size
else:
@@ -518,25 +560,27 @@ class NumberLine(Line):
self.add(labels)
return self
- @staticmethod
- def _create_label_tex(label_tex) -> "Mobject":
- """Checks if the label is a ``float``, ``int`` or a ``str`` and creates a :class:`~.MathTex`/:class:`~.Tex` label accordingly.
+ def _create_label_tex(self, label_tex: Union[str, float, VMobject]) -> VMobject:
+ """Checks if the label is a :class:`~.VMobject`, otherwise, creates a
+ label according to the ``label_constructor``.
Parameters
----------
- label_tex : The label to be compared against the above types.
+ label_tex
+ The label to be compared against the above types.
+ label_constructor
+ The VMobject class used to construct the label.
Returns
-------
- :class:`~.Mobject`
+ :class:`~.VMobject`
The label.
"""
- if isinstance(label_tex, (float, int)):
- label_tex = MathTex(label_tex)
- elif isinstance(label_tex, str):
- label_tex = Tex(label_tex)
- return label_tex
+ if isinstance(label_tex, VMobject):
+ return label_tex
+ else:
+ return self.label_constructor(label_tex)
@staticmethod
def _decimal_places_from_step(step) -> int:
diff --git a/manim/mobject/numbers.py b/manim/mobject/numbers.py
index edf7de02d..58a1ac3e9 100644
--- a/manim/mobject/numbers.py
+++ b/manim/mobject/numbers.py
@@ -50,6 +50,7 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
self,
number: float = 0,
num_decimal_places: int = 2,
+ mob_class: VMobject = MathTex,
include_sign: bool = False,
group_with_commas: bool = True,
digit_buff_per_font_unit: float = 0.001,
@@ -66,6 +67,7 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
self.number = number
self.num_decimal_places = num_decimal_places
self.include_sign = include_sign
+ self.mob_class = mob_class
self.group_with_commas = group_with_commas
self.digit_buff_per_font_unit = digit_buff_per_font_unit
self.show_ellipsis = show_ellipsis
@@ -168,9 +170,14 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
return num_string
- def string_to_mob(self, string, mob_class=MathTex, **kwargs):
+ def string_to_mob(
+ self, string: str, mob_class: Optional[VMobject] = None, **kwargs
+ ):
+ if mob_class is None:
+ mob_class = self.mob_class
+
if string not in string_to_mob_map:
- string_to_mob_map[string] = mob_class(string, font_size=1.0, **kwargs)
+ string_to_mob_map[string] = mob_class(string, **kwargs)
mob = string_to_mob_map[string].copy()
mob.font_size = self._font_size
return mob