Coverage for src/manimgx/mobjects/plotting.py: 96%

1095 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-26 05:52 +0000

1# SPDX-FileCopyrightText: 2026 Academa, Inc. 

2# SPDX-FileCopyrightText: 2024 the Manim Community Developers 

3# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC 

4# SPDX-License-Identifier: MIT 

5 

6"Coordinates, sampled functions, axes, planes and data drawn in those coordinates." 

7 

8from __future__ import annotations 

9 

10from warnings import deprecated 

11 

12__all__ = [ 

13 "Axes", 

14 "BarChart", 

15 "ComplexPlane", 

16 "FunctionGraph", 

17 "ImplicitFunction", 

18 "LinearBase", 

19 "LogBase", 

20 "NumberLine", 

21 "NumberPlane", 

22 "ParametricFunction", 

23 "PolarPlane", 

24 "SampleSpace", 

25 "ThreeDAxes", 

26 "UnitInterval", 

27] 

28 

29import fractions as fr 

30import math 

31from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence 

32from typing import ( 

33 TYPE_CHECKING, 

34 ClassVar, 

35 Literal, 

36 Self, 

37 Unpack, 

38 cast, 

39 overload, 

40) 

41 

42import numpy as np 

43import numpy.typing as npt 

44from isosurfaces import plot_isoline 

45from typing_extensions import TypedDict 

46 

47from manimgx.constants import ( 

48 DEFAULT_ARROW_TIP_LENGTH, 

49 DEFAULT_DOT_RADIUS, 

50 DEGREES, 

51 DL, 

52 DOWN, 

53 DR, 

54 LEFT, 

55 MED_SMALL_BUFF, 

56 ORIGIN, 

57 OUT, 

58 PI, 

59 RIGHT, 

60 SMALL_BUFF, 

61 TAU, 

62 UP, 

63 UR, 

64) 

65from manimgx.drawing.geometry import angle_of_vector, interpolate, normalize, sample 

66from manimgx.drawing.paint import ( 

67 BLACK, 

68 BLUE, 

69 BLUE_D, 

70 DARK_GREY, 

71 GREEN, 

72 LIGHT_GREY, 

73 MAROON_B, 

74 PURE_YELLOW, 

75 WHITE, 

76 YELLOW, 

77 Colorscale, 

78 ManimColor, 

79 ParsableManimColor, 

80 Style, 

81 StyleBase, 

82 _Style, 

83 color_gradient, 

84 colors_by_value, 

85 invert_color, 

86 parse_colors, 

87) 

88from manimgx.mobject import Group, Mobject, VDict, VGroup, VMobject 

89from manimgx.mobjects.numbers import DecimalNumber, DecimalNumberOptions, Integer 

90from manimgx.mobjects.shapes import ( 

91 ArrowTip, 

92 Circle, 

93 DashedLine, 

94 DashedLineOptions, 

95 Dot, 

96 Line, 

97 LineOptions, 

98 Polygon, 

99 Rectangle, 

100 RegularPolygon, 

101 Tipped, 

102 _Tipped, 

103) 

104from manimgx.mobjects.text import MathTex, MathTexOptions, Tex, Typst 

105from manimgx.settings import config 

106from manimgx.typing import ManimTextLabel, Vector3D 

107 

108if TYPE_CHECKING: 

109 from manimgx.typing import ( 

110 ManimTextLabel, 

111 Point3D, 

112 Point3D_Array, 

113 Point3DLike, 

114 Point3DLike_Array, 

115 Vector3D, 

116 Vector3DLike, 

117 ) 

118 

119 

120class _ScaleBase: 

121 """How numbers are laid along an axis: `function` maps a value to its position.""" 

122 

123 def __init__(self, custom_labels: bool = False): 

124 self.custom_labels = custom_labels 

125 

126 @overload 

127 def function(self, value: float) -> float: ... 

128 @overload 

129 def function(self, value: np.ndarray) -> np.ndarray: ... 

130 def function(self, value: float | np.ndarray) -> float | np.ndarray: 

131 """The number of the axis at a value of its range: 10² for 2, on a logarithmic 

132 axis. 

133 

134 Args: 

135 value: The value of the range; or an array of values. 

136 

137 Returns: 

138 The number; or the numbers, an array of the same shape. 

139 """ 

140 return self._function(value) 

141 

142 @overload 

143 def inverse_function(self, value: float) -> float: ... 

144 @overload 

145 def inverse_function(self, value: np.ndarray) -> np.ndarray: ... 

146 def inverse_function(self, value: float | np.ndarray) -> float | np.ndarray: 

147 """The value of the axis's range at one of its numbers: 2 for 100, on a 

148 logarithmic axis; the inverse of `function`. 

149 

150 Args: 

151 value: The number; or an array of numbers. 

152 

153 Returns: 

154 The value of the range; or the values, an array of the same shape. 

155 """ 

156 return self._inverse_function(value) 

157 

158 # a scale's own map, of a float to a float and of an array to an array 

159 def _function(self, value: float | np.ndarray) -> float | np.ndarray: 

160 raise NotImplementedError 

161 

162 def _inverse_function(self, value: float | np.ndarray) -> float | np.ndarray: 

163 raise NotImplementedError 

164 

165 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

166 def get_custom_labels( 

167 self, val_range: Iterable[float], unit_decimal_places: int = 0 

168 ) -> list[Mobject]: 

169 """Make the labels of numbers, as the scale writes them (a scale with 

170 `custom_labels`). 

171 

172 Args: 

173 val_range: The numbers. 

174 unit_decimal_places: The decimal places the labels are written with. 

175 

176 Returns: 

177 A new label for each number, in order. 

178 """ 

179 raise NotImplementedError # a scale with `custom_labels` makes its own 

180 

181 

182class LinearBase(_ScaleBase): 

183 """An even scale for a number line: its numbers evenly spaced along it, the numbers 

184 of its range times `scale_factor`. 

185 

186 It is a number line's default scale, and with a factor of 1 its numbers are those of 

187 its range. With another factor, the line keeps its length and its ticks, and its 

188 numbers are multiplied: with 2, a range `[-2, 2, 1]` is numbered from -4 to 4 in 

189 steps of 2, and [n2p][manimgx.NumberLine.n2p] places 4 at its end. Give it as a 

190 number line's `scaling`, or an axis's in an axis config. 

191 

192 Args: 

193 scale_factor: The factor from the numbers of the range to the numbers of the 

194 line. 

195 

196 Examples: 

197 ```python 

198 import manimgx as m 

199 

200 

201 class LinearBaseExample(m.Scene): 

202 def construct(self) -> None: 

203 plain = m.NumberLine( 

204 x_range=[-3, 3, 1], length=10, include_numbers=True 

205 ) 

206 doubled = m.NumberLine( 

207 x_range=[-3, 3, 1], 

208 length=10, 

209 include_numbers=True, 

210 scaling=m.LinearBase(scale_factor=2), 

211 color=m.BLUE, 

212 ) 

213 self.add(m.VGroup(plain, doubled).arrange(m.DOWN, buff=1.5)) 

214 ``` 

215 """ 

216 

217 def __init__(self, scale_factor: float = 1.0): 

218 super().__init__() 

219 self.scale_factor = scale_factor 

220 """The factor from the numbers of the range to the numbers of the line.""" 

221 

222 def _function(self, value: float | np.ndarray) -> float | np.ndarray: 

223 return self.scale_factor * value 

224 

225 def _inverse_function(self, value: float | np.ndarray) -> float | np.ndarray: 

226 return value / self.scale_factor 

227 

228 

229class LogBase(_ScaleBase): 

230 """A logarithmic scale for a number line: its range is of exponents, and its 

231 numbers are powers of `base`, spaced by their logarithms. 

232 

233 With base 10, a range `[0, 3, 1]` runs from 1 to 1000, a tick at each power of 10, 

234 and [n2p][manimgx.NumberLine.n2p] places 100 two thirds of the way along. Its 

235 numbers are all positive: 0 and negative numbers have no place on it. Give it as a 

236 number line's `scaling`, or an axis's in an axis config; then 

237 [plot][manimgx.Axes.plot] samples a function over the powers, and 

238 [add_coordinates][manimgx.Axes.add_coordinates] writes the axis's 

239 numbers as powers. 

240 

241 Args: 

242 base: The base of the powers. 

243 custom_labels: Whether the line's numbers are written as powers (10², 10³, …), 

244 rather than as decimals. 

245 

246 Examples: 

247 ```python 

248 import manimgx as m 

249 

250 

251 class LogBaseExample(m.Scene): 

252 def construct(self) -> None: 

253 ax = m.Axes( 

254 x_range=[0, 10, 1], 

255 y_range=[-2, 6, 1], 

256 x_length=11, 

257 y_length=6.5, 

258 tips=False, 

259 axis_config={"include_numbers": True, "font_size": 28}, 

260 y_axis_config={"scaling": m.LogBase()}, 

261 ) 

262 exponential = ax.plot(lambda x: 0.01 * 10 ** (0.8 * x), color=m.BLUE) 

263 square = ax.plot(lambda x: x**2, x_range=[0.1, 10], color=m.YELLOW) 

264 self.add(ax, exponential, square) 

265 ``` 

266 """ 

267 

268 def __init__(self, base: float = 10, custom_labels: bool = True): 

269 super().__init__() 

270 self.base = base 

271 """The base of the powers.""" 

272 self.custom_labels = custom_labels 

273 """Whether the line's numbers are written as powers of the base.""" 

274 

275 def _function(self, value: float | np.ndarray) -> float | np.ndarray: 

276 if isinstance(value, np.ndarray): 

277 return np.power(self.base, value) 

278 return float(self.base**value) 

279 

280 def _inverse_function(self, value: float | np.ndarray) -> float | np.ndarray: 

281 if np.any(np.asarray(value) <= 0): 

282 raise ValueError( 

283 "log(0) is undefined. Make sure the value is in the domain of the" 

284 " function" 

285 ) 

286 if isinstance(value, np.ndarray): 

287 return np.log(value) / np.log(self.base) 

288 return math.log(value, self.base) 

289 

290 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

291 def get_custom_labels( 

292 self, 

293 val_range: Iterable[float], 

294 unit_decimal_places: int = 0, 

295 **base_config: Unpack[DecimalNumberOptions], 

296 ) -> list[Mobject]: 

297 """Make the labels of numbers, written as powers of the base: 100 as 10². 

298 

299 A number line with `custom_labels` numbers its ticks with these. 

300 

301 Args: 

302 val_range: The numbers, all positive. 

303 unit_decimal_places: The decimal places the exponents are written with. 

304 **base_config: [Number keywords][manimgx.DecimalNumber] 

305 for the labels: each is an [Integer][manimgx.Integer], the base, with 

306 its exponent as its `unit`. 

307 

308 Returns: 

309 A new label for each number, in order, not placed. 

310 """ 

311 return [ 

312 Integer( 

313 self.base, 

314 **( 

315 base_config 

316 | { 

317 "unit": ( 

318 f"^{{{self.inverse_function(i):.{unit_decimal_places}f}}}" 

319 ) 

320 } 

321 ), 

322 ) 

323 for i in val_range 

324 ] 

325 

326 

327_CURVE_LINEAR = LinearBase() # a default (never changed) 

328 

329 

330class _CurveOptions(_Style, total=False): 

331 """CurveOptions's keys, open, for the keywords that add to them.""" 

332 

333 dt: float 

334 """How far short of each discontinuity the curve's pieces stop, in units of its 

335 parameter (default 1e-8).""" 

336 discontinuities: Iterable[float] | None 

337 """The values of the parameter where the curve breaks: it is drawn in pieces 

338 between them (default None: none).""" 

339 use_smoothing: bool 

340 """Whether the samples are joined by a smooth curve through them, rather than by 

341 straight segments (default True).""" 

342 

343 

344class CurveOptions(_CurveOptions, total=False, closed=True): 

345 """How a curve is sampled and smoothed, with the style keywords: the keywords of 

346 [plot][manimgx.Axes.plot] and the other curves, for the methods that 

347 pass them on.""" 

348 

349 

350class ParametricOptions(_CurveOptions, total=False): 

351 """A [ParametricFunction][manimgx.ParametricFunction]'s keywords but its function: 

352 its parameter's range and spacing, with the curve keywords.""" 

353 

354 t_range: Sequence[float] 

355 """The parameter's range, `[t_min, t_max]` or `[t_min, t_max, t_step]`: the 

356 function is sampled every `t_step`, 0.01 if not given (default [0, 1]).""" 

357 scaling: _ScaleBase 

358 """How the parameter is spaced over its range: evenly, with 

359 [LinearBase][manimgx.LinearBase]; with [LogBase][manimgx.LogBase], the range is of 

360 exponents, and the parameter runs over powers (default `LinearBase()`).""" 

361 use_vectorized: bool 

362 """Whether the function takes all the values of the parameter at once, as an 

363 array, and returns the arrays of x, y and z (default False).""" 

364 

365 

366class ParametricFunction(VMobject): 

367 """A parametric curve: the points `function(t)` for t from `t_min` to `t_max`, 

368 joined smoothly; white unless styled. 

369 

370 The function is sampled every `t_step`, and at `t_max`, and the samples are joined 

371 by a smooth curve through them (or by straight segments, without 

372 `use_smoothing`). Where the function jumps, give its `discontinuities`: the curve 

373 is drawn in pieces between them, each stopping `dt` short. The function is first 

374 tried on all the values of t at once, as an array, and checked against single calls 

375 (unless `use_vectorized` vouches for it); a function that does not take arrays is 

376 called once per value. 

377 

378 The discontinuities are kept as the list they were when the curve was made, before 

379 range filtering, so copies and regenerated curves keep all its breaks. 

380 

381 To graph a function on axes, in their coordinates, see [plot][manimgx.Axes.plot]. 

382 

383 Args: 

384 function: The function, from t to a point in scene coordinates: its x, y and z. 

385 t_range: The range of t, `[t_min, t_max]` or `[t_min, t_max, t_step]`; the 

386 step is 0.01 if not given. 

387 scaling: How t is spaced over its range: evenly, with 

388 [LinearBase][manimgx.LinearBase]; with [LogBase][manimgx.LogBase], the 

389 range is of exponents, and t runs over powers. 

390 dt: How far short of each discontinuity the pieces stop, in units of t. 

391 discontinuities: The values of t where the curve breaks; None for none. 

392 use_smoothing: Whether the samples are joined by a smooth curve through them, 

393 rather than by straight segments. 

394 use_vectorized: Whether `function` takes all the values of t at once, as an 

395 array, and gives what single calls would: it is then not checked against 

396 them. Its x, y and z may each be an array or one number for every t. 

397 

398 Examples: 

399 ```python 

400 import numpy as np 

401 

402 import manimgx as m 

403 

404 

405 class ParametricFunctionExample(m.Scene): 

406 def construct(self) -> None: 

407 lissajous = m.ParametricFunction( 

408 lambda t: np.array([2.5 * np.sin(2 * t), 2.5 * np.sin(3 * t), 0]), 

409 t_range=[0, m.TAU], 

410 color=m.BLUE, 

411 ) 

412 spiral = m.ParametricFunction( 

413 lambda t: np.array([0.15 * t * np.cos(t), 0.15 * t * np.sin(t), 0]), 

414 t_range=[0, 3 * m.TAU], 

415 color=m.YELLOW, 

416 ) 

417 curves = m.VGroup(lissajous, spiral).arrange(buff=1.5) 

418 self.play(m.Create(curves), run_time=3) 

419 ``` 

420 """ 

421 

422 underlying_function: Callable[[float], float] | None = None 

423 """The function y = f(x) the curve is the graph of, if it is one: 

424 [plot][manimgx.Axes.plot] and [FunctionGraph][manimgx.FunctionGraph] 

425 set it. None for other curves.""" 

426 

427 def __init__( 

428 self, 

429 function: Callable[[float], Point3DLike], 

430 t_range: Sequence[float] | np.ndarray = (0, 1), 

431 scaling: _ScaleBase = _CURVE_LINEAR, 

432 dt: float = 1e-08, 

433 discontinuities: Iterable[float] | None = None, 

434 use_smoothing: bool = True, 

435 use_vectorized: bool = False, 

436 **kwargs: Unpack[Style], 

437 ): 

438 

439 def internal_parametric_function(t: float) -> Point3D: 

440 return np.asarray(function(t)) 

441 

442 # sampled as given, on all the values of t at once if it can be: a function, as 

443 # copies share one, whatever callable was given 

444 def given(t: float) -> Point3DLike: 

445 return function(t) 

446 

447 self.function = internal_parametric_function 

448 """The curve's function: from t to its point, as an array.""" 

449 self._given = given 

450 if len(t_range) == 2: 

451 t_range = (*t_range, 0.01) 

452 self.scaling = scaling 

453 self.dt = dt 

454 self.discontinuities = ( 

455 None if discontinuities is None else list(discontinuities) 

456 ) 

457 self.use_smoothing = use_smoothing 

458 self.use_vectorized = use_vectorized 

459 self.t_min, self.t_max, self.t_step = t_range 

460 super().__init__(**kwargs) 

461 

462 def get_function(self) -> Callable[[float], Point3D]: 

463 """The curve's function: from t to its point. 

464 

465 Returns: 

466 The function, which returns an array. 

467 """ 

468 return self.function 

469 

470 def get_point_from_function(self, t: float, /) -> Point3D: 

471 """The curve's point at a value of t, from its function: past `t_range` too. 

472 

473 Args: 

474 t: The value of t. 

475 

476 Returns: 

477 The point, in scene coordinates. 

478 """ 

479 return self.function(t) 

480 

481 def generate_points(self) -> Self: 

482 if self.discontinuities is not None: 

483 values = self.discontinuities 

484 discontinuities = filter(lambda t: self.t_min <= t <= self.t_max, values) 

485 discontinuities_array = np.array(list(discontinuities)) 

486 boundary_times = np.array( 

487 [ 

488 self.t_min, 

489 self.t_max, 

490 *discontinuities_array - self.dt, 

491 *discontinuities_array + self.dt, 

492 ] 

493 ) 

494 boundary_times.sort() 

495 else: 

496 boundary_times = [self.t_min, self.t_max] 

497 for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2], strict=True): 

498 t_range = np.array( 

499 [ 

500 *self.scaling.function(np.arange(t1, t2, self.t_step)), 

501 self.scaling.function(t2), 

502 ] 

503 ) 

504 points = sample(self._given, t_range, checked=not self.use_vectorized) 

505 self.start_new_path(points[0]) 

506 self.add_points_as_corners(points[1:]) 

507 if self.use_smoothing: 

508 self.make_smooth() 

509 return self 

510 

511 

512class FunctionGraph(ParametricFunction): 

513 """The graph of a function y = f(x), in scene coordinates: the points (x, f(x), 0), 

514 joined smoothly; bright yellow (`PURE_YELLOW`) unless styled. 

515 

516 The sampler may call the function with arrays and individual values, falling 

517 back to scalar evaluation when needed. The number of callback calls is not 

518 guaranteed. 

519 

520 To graph a function on axes, in their coordinates, see 

521 [plot][manimgx.Axes.plot]. 

522 

523 Args: 

524 function: The function, from x to y. 

525 x_range: The range of x, `[x_min, x_max]` or `[x_min, x_max, x_step]`; the 

526 step is 0.01 if not given. None for the frame's width. 

527 

528 Examples: 

529 ```python 

530 import numpy as np 

531 

532 import manimgx as m 

533 

534 

535 class FunctionGraphExample(m.Scene): 

536 def construct(self) -> None: 

537 wave = m.FunctionGraph( 

538 lambda x: np.sin(x) + 0.5 * np.sin(7 * x) + np.sin(14 * x) / 7, 

539 color=m.BLUE, 

540 ) 

541 bell = m.FunctionGraph( 

542 lambda x: 3 * np.exp(-(x**2)), x_range=[-4, 4], color=m.YELLOW 

543 ) 

544 self.play(m.Create(wave), m.Create(bell), run_time=2) 

545 ``` 

546 """ 

547 

548 defaults: ClassVar[Style] = {"color": PURE_YELLOW} 

549 

550 def __init__( 

551 self, 

552 function: Callable[[float], float], 

553 x_range: Sequence[float] | None = None, 

554 **kwargs: Unpack[Style], 

555 ) -> None: 

556 if x_range is None: 

557 x_range = (-config.frame_x_radius, config.frame_x_radius) 

558 self.x_range = x_range 

559 """The range of x the graph spans, `[x_min, x_max]` or `[x_min, x_max, 

560 x_step]`.""" 

561 self.parametric_function: Callable[[float], Point3D] = lambda t: np.array( 

562 np.broadcast_arrays(t, function(t), 0) 

563 if isinstance(t, np.ndarray) 

564 else [t, function(t), 0] 

565 ) 

566 """The graph's point function: from x to the point (x, f(x), 0).""" 

567 super().__init__(self.parametric_function, self.x_range, **kwargs) 

568 self.underlying_function = function 

569 

570 def get_point_from_function(self, x: float, /) -> Point3D: 

571 return self.parametric_function(x) 

572 

573 

574class ImplicitOptions(_Style, total=False, closed=True): 

575 """An [ImplicitFunction][manimgx.ImplicitFunction]'s smoothing, with the style 

576 keywords, for the methods that pass them on 

577 ([plot_implicit_curve][manimgx.Axes.plot_implicit_curve]).""" 

578 

579 use_smoothing: bool 

580 """Whether the curve is smoothed through its points, rather than drawn in straight 

581 segments (default True).""" 

582 

583 

584class ImplicitFunction(VMobject): 

585 """The curve where a function of x and y is zero, `func(x, y) = 0`, in scene 

586 coordinates, found within a rectangle; white unless styled. 

587 

588 The rectangle is divided in four, and each part in four again, finer where the 

589 curve passes, and the curve is traced through the cells: one path for each of its 

590 pieces. To plot on axes, in their coordinates, see 

591 [plot_implicit_curve][manimgx.Axes.plot_implicit_curve]. 

592 

593 Args: 

594 func: The function of x and y, in scene coordinates. 

595 x_range: The range of x to look in, `[x_min, x_max]`; None for the frame's 

596 width. 

597 y_range: The range of y to look in, `[y_min, y_max]`; None for the frame's 

598 height. 

599 min_depth: How many times the rectangle is at least divided in four: more 

600 finds smaller pieces of the curve. 

601 max_quads: The most cells the rectangle may be divided into: more follow the 

602 curve more closely, and take longer. 

603 use_smoothing: Whether the curve is smoothed through its points, rather than 

604 drawn in straight segments. 

605 

606 Examples: 

607 ```python 

608 import manimgx as m 

609 

610 

611 class ImplicitFunctionExample(m.Scene): 

612 def construct(self) -> None: 

613 cubic = m.ImplicitFunction( 

614 lambda x, y: x * y**2 - x**2 * y - 2, color=m.YELLOW 

615 ) 

616 heart = m.ImplicitFunction( 

617 lambda x, y: (x**2 + y**2 - 1) ** 3 - x**2 * y**3, 

618 x_range=[-1.5, 1.5], 

619 y_range=[-1.5, 1.5], 

620 color=m.RED, 

621 ).scale(1.5) 

622 self.add(m.NumberPlane(), cubic, heart) 

623 ``` 

624 """ 

625 

626 def __init__( 

627 self, 

628 func: Callable[[float, float], float], 

629 x_range: Sequence[float] | None = None, 

630 y_range: Sequence[float] | None = None, 

631 min_depth: int = 5, 

632 max_quads: int = 1500, 

633 use_smoothing: bool = True, 

634 **kwargs: Unpack[Style], 

635 ): 

636 self.function = func 

637 """The function whose zeros the curve is.""" 

638 self.min_depth = min_depth 

639 self.max_quads = max_quads 

640 self.use_smoothing = use_smoothing 

641 self.x_range = x_range or [-config.frame_width / 2, config.frame_width / 2] 

642 self.y_range = y_range or [-config.frame_height / 2, config.frame_height / 2] 

643 super().__init__(**kwargs) 

644 

645 def generate_points(self) -> Self: 

646 p_min, p_max = ( 

647 np.array([self.x_range[0], self.y_range[0]]), 

648 np.array([self.x_range[1], self.y_range[1]]), 

649 ) 

650 curves = plot_isoline( 

651 fn=lambda u: self.function(u[0], u[1]), 

652 pmin=p_min, 

653 pmax=p_max, 

654 min_depth=self.min_depth, 

655 max_quads=self.max_quads, 

656 ) 

657 curves = [np.pad(curve, [(0, 0), (0, 1)]) for curve in curves if curve != []] 

658 for curve in curves: 

659 self.start_new_path(curve[0]) 

660 self.add_points_as_corners(curve[1:]) 

661 if self.use_smoothing: 

662 self.make_smooth() 

663 return self 

664 

665 

666type Label = float | str | Mobject 

667 

668 

669"""A label: a mobject, used as it is, or a number or a string, typeset (as math, by 

670default).""" 

671 

672 

673_AXIS_LINEAR = LinearBase() # a default (never changed) 

674 

675 

676class NumberLineOptions(_Tipped, total=False, closed=True): 

677 """A [NumberLine][manimgx.NumberLine]'s keywords but its range, for the configs that 

678 pass them on (a coordinate system's axes): its size, ticks, tip and numbers, with 

679 the style and tip keywords.""" 

680 

681 length: float | None 

682 """The line's length, in scene units (default None: `unit_size` per unit).""" 

683 unit_size: float 

684 """The length of one unit, in scene units, when `length` is not given (default 

685 1).""" 

686 include_ticks: bool 

687 """Whether to draw the ticks (default True).""" 

688 tick_size: float 

689 """How far each tick reaches on either side of the line, in scene units: half its 

690 length (default 0.1).""" 

691 numbers_with_elongated_ticks: Iterable[float] | None 

692 """The numbers whose ticks are longer (default None: none).""" 

693 longer_tick_multiple: int 

694 """How many times longer those ticks are (default 2).""" 

695 exclude_origin_tick: bool 

696 """Whether to leave out the tick at 0 (default False; an axis of 

697 [Axes][manimgx.Axes] leaves it out, when linear, for the other axis crosses 

698 there).""" 

699 rotation: float 

700 """The angle the line is turned through about its center, in radians, 

701 counterclockwise (default 0; a y-axis's is a quarter turn).""" 

702 include_tip: bool 

703 """Whether the line ends in an arrow tip, at its end (default False; an axis's 

704 does, unless `tips=False`).""" 

705 tip_width: float 

706 """The tip's width, in scene units (default 0.35).""" 

707 tip_height: float 

708 """The tip's length, along the line, in scene units (default 0.35).""" 

709 tip_shape: type[ArrowTip] | None 

710 """The class of the tip (default None: 

711 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip]).""" 

712 include_numbers: bool 

713 """Whether to number the ticks (default False).""" 

714 font_size: float 

715 """The numbers' font size (default 36).""" 

716 label_direction: Vector3DLike 

717 """The side of the line the numbers go on, as a direction (default DOWN: below; a 

718 y-axis's are on its left).""" 

719 label_constructor: type[ManimTextLabel] 

720 """The class the numbers and labels are typeset with (default 

721 [MathTex][manimgx.MathTex]).""" 

722 scaling: _ScaleBase 

723 """How numbers are spaced along the line: evenly, with 

724 [LinearBase][manimgx.LinearBase], or by their logarithms, with 

725 [LogBase][manimgx.LogBase] (default `LinearBase()`).""" 

726 line_to_number_buff: float 

727 """The gap between the line and its numbers, in scene units (default 0.25).""" 

728 decimal_number_config: DecimalNumberOptions | None 

729 """[Number keywords][manimgx.DecimalNumber] for the 

730 numbers (default None: as many decimal places as the range's step has, or its 

731 start, when the range is all on one side of 0).""" 

732 numbers_to_exclude: Iterable[float] | None 

733 """Numbers not to write, when the ticks are numbered (default None: none; an 

734 axis's leave out 0).""" 

735 numbers_to_include: Iterable[float] | None 

736 """The numbers to write, instead of the ticks': given, they are written even 

737 without `include_numbers` (default None: the ticks').""" 

738 

739 

740def _along(offsets: np.ndarray, direction: Vector3D) -> np.ndarray: 

741 """The projections of an offset, or of an array of them, onto a unit direction. Along a 

742 coordinate axis, as a straight number line runs, a projection is that coordinate times 

743 ±1: what the dot product gives in any order of summing, so that a point's number is the 

744 same alone and among others.""" 

745 (nonzero,) = np.nonzero(direction) 

746 if len(nonzero) == 1: 

747 return offsets[..., nonzero[0]] * direction[nonzero[0]] 

748 return np.dot(offsets, direction) 

749 

750 

751class NumberLine(Line): 

752 """A number line: a line with ticks at every step of its range, numbers if asked 

753 for, and a map between numbers and points; white, with a stroke 2 wide, unless 

754 styled. 

755 

756 Its range, `[x_min, x_max, x_step]`, runs from its left end to its right end: the 

757 line is `length` long, in scene units, or `unit_size` per unit, and it is centered 

758 on the scene's origin (then turned through `rotation`). Its ticks are `x_step` 

759 apart, counted from 0 when the range contains it (from `x_min` otherwise); a tip at 

760 its end takes the place of the last tick. 

761 [number_to_point][manimgx.NumberLine.number_to_point] and 

762 [point_to_number][manimgx.NumberLine.point_to_number] convert between numbers and 

763 points; [add_numbers][manimgx.NumberLine.add_numbers] and 

764 [add_labels][manimgx.NumberLine.add_labels] write on it. A `scaling` spaces the 

765 numbers otherwise: with [LogBase][manimgx.LogBase], the range is of exponents, and 

766 the line's numbers are powers. 

767 

768 Initial length, rotation, tip dimensions and which ticks/numbers to draw are 

769 construction inputs, not retained attributes. The line keeps its drawing and 

770 the defaults used by later tick and label methods; the numbers to exclude and 

771 those with elongated ticks are kept as the lists they were when it was made. 

772 

773 Args: 

774 x_range: The range, `[x_min, x_max, x_step]`, or `[x_min, x_max]` for a step of 

775 1; None for [-7, 7, 1]. 

776 length: The line's length, in scene units; None for `unit_size` per unit. 

777 unit_size: The length of one unit, in scene units, when `length` is None. 

778 include_ticks: Whether to draw the ticks. 

779 tick_size: How far each tick reaches on either side of the line, in scene 

780 units: half its length. 

781 numbers_with_elongated_ticks: The numbers whose ticks are longer; None for 

782 none. 

783 longer_tick_multiple: How many times longer those ticks are. 

784 exclude_origin_tick: Whether to leave out the tick at 0. 

785 rotation: The angle the line is turned through about its center, in radians, 

786 counterclockwise. 

787 include_tip: Whether the line ends in an arrow tip, at its end. 

788 tip_width: The tip's width, in scene units. 

789 tip_height: The tip's length, along the line, in scene units. 

790 tip_shape: The class of the tip; None for 

791 [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip]. 

792 include_numbers: Whether to number the ticks (see 

793 [add_numbers][manimgx.NumberLine.add_numbers]). 

794 font_size: The numbers' font size. 

795 label_direction: The side of the line the numbers go on, as a direction: DOWN 

796 for below. 

797 label_constructor: The class the numbers and labels are typeset with: 

798 [MathTex][manimgx.MathTex], [MathTypst][manimgx.MathTypst], …. 

799 scaling: How numbers are spaced along the line: evenly, with 

800 [LinearBase][manimgx.LinearBase], or by their logarithms, with 

801 [LogBase][manimgx.LogBase] (its numbers are then written as powers). 

802 line_to_number_buff: The gap between the line and its numbers, in scene units. 

803 decimal_number_config: The numbers' 

804 [number keywords][manimgx.DecimalNumber]; None 

805 for as many decimal places as `x_step` has, or the range's start, when 

806 the range is all on one side of 0 and its ticks count from there. 

807 numbers_to_exclude: Numbers not to write, when the ticks are numbered; None 

808 for none. 

809 numbers_to_include: The numbers to write, instead of the ticks': given, they 

810 are written even without `include_numbers`. None for the ticks'. 

811 

812 Examples: 

813 ```python 

814 import manimgx as m 

815 

816 

817 class NumberLineExample(m.Scene): 

818 def construct(self) -> None: 

819 lines = m.VGroup( 

820 m.NumberLine(x_range=[-5, 5, 1], length=12, include_numbers=True), 

821 m.NumberLine( 

822 x_range=[0, 2, 0.25], 

823 length=12, 

824 include_numbers=True, 

825 font_size=28, 

826 color=m.BLUE, 

827 ), 

828 m.NumberLine( 

829 x_range=[-10, 10, 2], 

830 length=12, 

831 numbers_with_elongated_ticks=[-10, 0, 10], 

832 include_tip=True, 

833 include_numbers=True, 

834 label_direction=m.UP, 

835 color=m.YELLOW, 

836 ), 

837 ).arrange(m.DOWN, buff=1) 

838 self.add(lines) 

839 ``` 

840 """ 

841 

842 defaults: ClassVar[Style] = {"stroke_width": 2.0} 

843 

844 def __init__( 

845 self, 

846 x_range: Sequence[float] | None = None, 

847 length: float | None = None, 

848 unit_size: float = 1, 

849 include_ticks: bool = True, 

850 tick_size: float = 0.1, 

851 numbers_with_elongated_ticks: Iterable[float] | None = None, 

852 longer_tick_multiple: int = 2, 

853 exclude_origin_tick: bool = False, 

854 rotation: float = 0, 

855 include_tip: bool = False, 

856 tip_width: float = DEFAULT_ARROW_TIP_LENGTH, 

857 tip_height: float = DEFAULT_ARROW_TIP_LENGTH, 

858 tip_shape: type[ArrowTip] | None = None, 

859 include_numbers: bool = False, 

860 font_size: float = 36, 

861 label_direction: Vector3DLike = DOWN, 

862 label_constructor: type[ManimTextLabel] = MathTex, 

863 scaling: _ScaleBase = _AXIS_LINEAR, 

864 line_to_number_buff: float = MED_SMALL_BUFF, 

865 decimal_number_config: DecimalNumberOptions | None = None, 

866 numbers_to_exclude: Iterable[float] | None = None, 

867 numbers_to_include: Iterable[float] | None = None, 

868 **kwargs: Unpack[Tipped], 

869 ): 

870 # values, as they are given: what the line keeps is its own 

871 numbers_to_exclude = ( 

872 [] if numbers_to_exclude is None else list(numbers_to_exclude) 

873 ) 

874 numbers_with_elongated_ticks = ( 

875 [] 

876 if numbers_with_elongated_ticks is None 

877 else list(numbers_with_elongated_ticks) 

878 ) 

879 if x_range is None: 

880 x_range = [ 

881 round(-config.frame_x_radius), 

882 round(config.frame_x_radius), 

883 1, 

884 ] 

885 elif len(x_range) == 2: 

886 x_range = [*x_range, 1] 

887 if decimal_number_config is None: 

888 # a whole float step keeps its one place: (0, 3, 1.0) is written 1.0, 2.0 

889 places = max( 

890 self._decimal_places_of(x_range[2]), 

891 int(str(x_range[2]).endswith(".0")), 

892 ) 

893 if 0 < x_range[0] < x_range[1] or x_range[0] < x_range[1] < 0: 

894 # ticks count from the start, not from 0 (see get_tick_range) 

895 places = max(places, self._decimal_places_of(x_range[0])) 

896 decimal_number_config = {"num_decimal_places": places} 

897 self.x_range = np.array(x_range, dtype=float) 

898 """The line's range, `[x_min, x_max, x_step]`, as given: of exponents, on a 

899 logarithmic line.""" 

900 self.x_min: float 

901 """The line's number at its start: the first of its range, scaled (10⁰ = 1 for 

902 a range from 0, on a logarithmic line).""" 

903 self.x_max: float 

904 """The line's number at its end: the second of its range, scaled.""" 

905 self.x_step: float 

906 """The step of its range, scaled.""" 

907 self.x_min, self.x_max, self.x_step = scaling.function(self.x_range) 

908 self.unit_size = unit_size 

909 """The length of one unit, in scene units, as the line was made; see 

910 [get_unit_size][manimgx.NumberLine.get_unit_size] for its length now.""" 

911 self.tick_size = tick_size 

912 self.numbers_with_elongated_ticks = numbers_with_elongated_ticks 

913 self.longer_tick_multiple = longer_tick_multiple 

914 self.exclude_origin_tick = exclude_origin_tick 

915 self.include_tip = include_tip 

916 self.font_size = font_size 

917 self.label_direction = label_direction 

918 self.label_constructor = label_constructor 

919 self.line_to_number_buff = line_to_number_buff 

920 self.decimal_number_config = decimal_number_config 

921 self.numbers_to_exclude = numbers_to_exclude 

922 self.scaling = scaling 

923 """How the line's numbers are spaced along it.""" 

924 super().__init__(self.x_range[0] * RIGHT, self.x_range[1] * RIGHT, **kwargs) 

925 if length: 

926 self.set_length(length) 

927 self.unit_size = self.get_unit_size() 

928 else: 

929 self.scale(self.unit_size) 

930 self.center() 

931 if self.include_tip: 

932 self.add_tip( 

933 tip_length=tip_height, 

934 tip_width=tip_width, 

935 tip_shape=tip_shape, 

936 ) 

937 self.tip.set_stroke(self.stroke_color, self.stroke_width) 

938 if include_ticks: 

939 self.add_ticks() 

940 self.rotate(rotation) 

941 if include_numbers or numbers_to_include is not None: 

942 if self.scaling.custom_labels: 

943 tick_range = self.get_tick_range() 

944 custom_labels = self.scaling.get_custom_labels( 

945 tick_range, 

946 unit_decimal_places=decimal_number_config.get( 

947 "num_decimal_places", 0 

948 ), 

949 ) 

950 self.add_labels(dict(zip(tick_range, custom_labels, strict=True))) 

951 else: 

952 self.add_numbers( 

953 x_values=numbers_to_include, excluding=self.numbers_to_exclude 

954 ) 

955 

956 def rotate_about_zero(self, angle: float, axis: Vector3DLike = OUT) -> Self: 

957 """Turn the line about the point of its number 0. 

958 

959 Args: 

960 angle: The angle, in radians, counterclockwise about `axis`. 

961 axis: The axis of the turn: OUT turns it in the plane of the screen. 

962 """ 

963 return self.rotate_about_number(0, angle, axis) 

964 

965 def rotate_about_number( 

966 self, number: float, angle: float, axis: Vector3DLike = OUT 

967 ) -> Self: 

968 """Turn the line about the point of one of its numbers. 

969 

970 Args: 

971 number: The number whose point stays fixed. 

972 angle: The angle, in radians, counterclockwise about `axis`. 

973 axis: The axis of the turn: OUT turns it in the plane of the screen. 

974 """ 

975 return self.rotate(angle, axis, about_point=self.n2p(number)) 

976 

977 @deprecated("Manim CE's machinery: the constructor calls it", category=None) 

978 def add_ticks(self) -> Self: 

979 """Add the line's ticks: one at each number of its 

980 [tick range][manimgx.NumberLine.get_tick_range], across the line, those of 

981 `numbers_with_elongated_ticks` longer. 

982 

983 The constructor calls it, unless `include_ticks` is False. The ticks are a group 

984 added to the line, and kept as its `ticks`. 

985 """ 

986 ticks = VGroup() 

987 elongated_tick_size = self.tick_size * self.longer_tick_multiple 

988 elongated_tick_offsets = ( 

989 np.array(self.numbers_with_elongated_ticks) - self.x_min 

990 ) 

991 for x in self.get_tick_range(): 

992 size = self.tick_size 

993 if np.any(np.isclose(x - self.x_min, elongated_tick_offsets)): 

994 size = elongated_tick_size 

995 ticks.add(self.get_tick(x, size)) 

996 self.add(ticks) 

997 self.ticks = ticks 

998 return self 

999 

1000 @deprecated("Manim CE's machinery: the constructor calls it", category=None) 

1001 def get_tick(self, x: float, size: float | None = None) -> Line: 

1002 """Make a tick for a number: a short line across the number line at the 

1003 number's point, in the line's style. 

1004 

1005 Args: 

1006 x: The number. 

1007 size: How far the tick reaches on either side of the line, in scene units; 

1008 None for the line's `tick_size`. 

1009 

1010 Returns: 

1011 A new line, not added to the number line. 

1012 """ 

1013 if size is None: 

1014 size = self.tick_size 

1015 result = Line(size * DOWN, size * UP) 

1016 result.rotate(self.get_angle()) 

1017 result.move_to(self.number_to_point(x)) 

1018 result.match_style(self) 

1019 return result 

1020 

1021 @deprecated("Manim CE's machinery: the constructor calls it", category=None) 

1022 def get_tick_range(self) -> np.ndarray: 

1023 """The numbers the line's ticks are at. 

1024 

1025 They are `x_step` apart, counted from 0 outward when the range contains it 

1026 (from `x_min` otherwise), up to `x_max` included — excluded if the line has a 

1027 tip — and without 0 if `exclude_origin_tick`. On a scaled line they are the 

1028 numbers themselves: powers, on a logarithmic one. 

1029 

1030 Returns: 

1031 An array of the numbers, in increasing order. 

1032 """ 

1033 x_min, x_max, x_step = self.x_range 

1034 if not self.include_tip: 

1035 x_max += 1e-06 

1036 if x_min < x_max < 0 or x_max > x_min > 0: 

1037 tick_range = np.arange(x_min, x_max, x_step) 

1038 else: 

1039 start_point = 0 

1040 if self.exclude_origin_tick: 

1041 start_point += x_step 

1042 x_min_segment = np.arange(start_point, np.abs(x_min) + 1e-06, x_step) * -1 

1043 x_max_segment = np.arange(start_point, x_max, x_step) 

1044 tick_range = np.unique(np.concatenate((x_min_segment, x_max_segment))) 

1045 return self.scaling.function(tick_range) 

1046 

1047 def number_to_point(self, number: float | np.ndarray) -> np.ndarray: 

1048 """Convert a number to its point on the line, or numbers to their points. 

1049 

1050 A number outside the range is on the line extended past its ends. 

1051 

1052 Args: 

1053 number: The number; or an array of numbers, of any shape. 

1054 

1055 Returns: 

1056 The point, in scene coordinates; for an array, the points, with the 

1057 coordinates last (the array's shape, then 3). 

1058 

1059 Examples: 

1060 ```python 

1061 import manimgx as m 

1062 

1063 

1064 class NumberLineNumberToPointExample(m.Scene): 

1065 def construct(self) -> None: 

1066 line = m.NumberLine( 

1067 x_range=[-4, 4, 1], length=12, include_numbers=True 

1068 ) 

1069 dot = m.Dot(line.n2p(-3), radius=0.15, color=m.YELLOW) 

1070 self.add(line, dot) 

1071 self.play(dot.animate.move_to(line.n2p(2.5))) 

1072 ``` 

1073 """ 

1074 number = self.scaling.inverse_function(np.asarray(number, dtype=float)) 

1075 alphas = (number - self.x_range[0]) / (self.x_range[1] - self.x_range[0]) 

1076 start, end = self.get_start(), self.get_end() 

1077 a = np.asarray(alphas)[..., None] 

1078 return (1 - a) * start + a * end 

1079 

1080 def point_to_number(self, point: Point3DLike) -> float: 

1081 """Convert a point to the number at its projection on the line: the inverse of 

1082 [number_to_point][manimgx.NumberLine.number_to_point] for points on the line. 

1083 

1084 Args: 

1085 point: The point, in scene coordinates. 

1086 """ 

1087 point = np.asarray(point, dtype=float) 

1088 start, end = self.get_start(), self.get_end() 

1089 unit_vect = normalize(end - start) 

1090 proportion: float = _along(point - start, unit_vect) / np.dot( 

1091 end - start, unit_vect 

1092 ) 

1093 # along the range, then through the scale, as number_to_point goes back 

1094 return self.scaling.function( 

1095 interpolate(self.x_range[0], self.x_range[1], proportion) 

1096 ) 

1097 

1098 def n2p(self, number: float | np.ndarray) -> Point3D: 

1099 """Convert a number to its point on the line: 

1100 [number_to_point][manimgx.NumberLine.number_to_point], by a shorter name. 

1101 

1102 Args: 

1103 number: The number; or an array of numbers, of any shape. 

1104 

1105 Returns: 

1106 The point, in scene coordinates; or the points. 

1107 """ 

1108 return self.number_to_point(number) 

1109 

1110 def get_unit_size(self) -> float: 

1111 """The length of one unit of the line: its length over its range. 

1112 

1113 Returns: 

1114 The length, in scene units (of one unit of exponent, on a logarithmic 

1115 line). 

1116 """ 

1117 val: float = self.get_length() / (self.x_range[1] - self.x_range[0]) 

1118 return val 

1119 

1120 def get_unit_vector(self) -> Vector3D: 

1121 """The line's direction, one unit long: the vector from its start toward its 

1122 end, as long as the unit the line was made with (its `unit_size`). 

1123 

1124 Returns: 

1125 The vector, in scene units. 

1126 """ 

1127 return super().get_unit_vector() * self.unit_size 

1128 

1129 def get_number_mobject( 

1130 self, 

1131 x: float, 

1132 direction: Vector3DLike | None = None, 

1133 buff: float | None = None, 

1134 label_constructor: type[ManimTextLabel] | None = None, 

1135 **number_config: Unpack[DecimalNumberOptions], 

1136 ) -> VMobject: 

1137 """Make a number, written beside its point on the line. 

1138 

1139 It is a [DecimalNumber][manimgx.DecimalNumber] in the line's number style (its 

1140 `decimal_number_config` and `font_size`), with `number_config` over it. A 

1141 negative number written straight below or above the line is shifted so its 

1142 digits, not its minus sign, are centered on the point. 

1143 

1144 Args: 

1145 x: The number. 

1146 direction: The side of the line it goes on; None for the line's 

1147 `label_direction`. 

1148 buff: The gap between the line and the number, in scene units; None for the 

1149 line's `line_to_number_buff`. 

1150 label_constructor: The class it is typeset with; None for the line's. 

1151 **number_config: [Number keywords][manimgx.DecimalNumber], 

1152 over the line's. 

1153 

1154 Returns: 

1155 A new number, not added to the line. 

1156 """ 

1157 options = self.decimal_number_config | number_config 

1158 options.setdefault("font_size", self.font_size) 

1159 options["mob_class"] = label_constructor or self.label_constructor 

1160 num_mob = DecimalNumber(x, **options) 

1161 num_mob.next_to( 

1162 self.number_to_point(x), 

1163 direction=self.label_direction if direction is None else direction, 

1164 buff=self.line_to_number_buff if buff is None else buff, 

1165 ) 

1166 if x < 0 and self.label_direction[0] == 0: 

1167 num_mob.shift(num_mob[0].width * LEFT / 2) 

1168 return num_mob 

1169 

1170 def add_numbers( 

1171 self, 

1172 x_values: Iterable[float] | None = None, 

1173 excluding: Iterable[float] | None = None, 

1174 label_constructor: type[ManimTextLabel] | None = None, 

1175 **kwargs: Unpack[DecimalNumberOptions], 

1176 ) -> Self: 

1177 """Number the line: write numbers beside the points of the given values, or of 

1178 its ticks. 

1179 

1180 Each number is written as 

1181 [get_number_mobject][manimgx.NumberLine.get_number_mobject] writes it. The 

1182 numbers are a group added to the line, and kept as its `numbers`. 

1183 

1184 Args: 

1185 x_values: The numbers to write; None for the ticks' numbers. 

1186 excluding: Numbers not to write; None for the line's `numbers_to_exclude`. 

1187 label_constructor: The class they are typeset with; None for the line's. 

1188 **kwargs: [Number keywords][manimgx.DecimalNumber], 

1189 over the line's: `font_size`, `num_decimal_places`, `color`, …. 

1190 

1191 Examples: 

1192 ```python 

1193 import manimgx as m 

1194 

1195 

1196 class NumberLineAddNumbersExample(m.Scene): 

1197 def construct(self) -> None: 

1198 ticks = m.NumberLine(x_range=[0, 10, 1], length=12).add_numbers() 

1199 chosen = m.NumberLine(x_range=[0, 10, 1], length=12, color=m.BLUE) 

1200 chosen.add_numbers( 

1201 [0, 2.5, 5, 7.5, 10], num_decimal_places=1, color=m.BLUE 

1202 ) 

1203 self.add(m.VGroup(ticks, chosen).arrange(m.DOWN, buff=1.5)) 

1204 ``` 

1205 """ 

1206 if x_values is None: 

1207 x_values = self.get_tick_range() 

1208 excluded = list(self.numbers_to_exclude if excluding is None else excluding) 

1209 numbers = VGroup() 

1210 for x in x_values: 

1211 if x in excluded: 

1212 continue 

1213 numbers.add( 

1214 self.get_number_mobject( 

1215 x, label_constructor=label_constructor, **kwargs 

1216 ) 

1217 ) 

1218 self.add(numbers) 

1219 self.numbers = numbers 

1220 return self 

1221 

1222 def add_labels( 

1223 self, 

1224 dict_values: Mapping[float, Label], 

1225 direction: Point3DLike | None = None, 

1226 buff: float | None = None, 

1227 font_size: float | None = None, 

1228 label_constructor: type[ManimTextLabel] | None = None, 

1229 ) -> Self: 

1230 r"""Label the line: put each label beside the point of its number. 

1231 

1232 A string is typeset as text with [Tex][manimgx.Tex] when the constructor is 

1233 [MathTex][manimgx.MathTex] (as by default), and with the constructor otherwise; 

1234 a number is written with the constructor. A mobject is used as it is, and must 

1235 be typeset (a [Typst][manimgx.Typst] mobject: [Text][manimgx.Text], 

1236 [Tex][manimgx.Tex], [MathTex][manimgx.MathTex], …) or a 

1237 [DecimalNumber][manimgx.DecimalNumber]: another raises an exception. Every label 

1238 is set to `font_size`. The labels are a group added to the line, and kept as its 

1239 `labels`. 

1240 

1241 Args: 

1242 dict_values: The labels, by number. 

1243 direction: The side of the line they go on, as a direction; None for the 

1244 line's `label_direction`. 

1245 buff: The gap between the line and the labels, in scene units; None for the 

1246 line's `line_to_number_buff`. 

1247 font_size: The labels' font size; None for the line's. 

1248 label_constructor: The class strings and numbers are typeset with; None for 

1249 the line's. 

1250 

1251 Examples: 

1252 ```python 

1253 import manimgx as m 

1254 

1255 

1256 class NumberLineAddLabelsExample(m.Scene): 

1257 def construct(self) -> None: 

1258 line = m.NumberLine(x_range=[0, m.TAU, m.PI / 2], length=12) 

1259 line.add_labels( 

1260 { 

1261 0: "0", 

1262 m.PI / 2: m.MathTex(r"\frac{\pi}{2}"), 

1263 m.PI: m.MathTex(r"\pi"), 

1264 3 * m.PI / 2: m.MathTex(r"\frac{3\pi}{2}"), 

1265 m.TAU: m.MathTex(r"2\pi"), 

1266 }, 

1267 font_size=44, 

1268 ) 

1269 self.add(line) 

1270 ``` 

1271 """ 

1272 direction = self.label_direction if direction is None else direction 

1273 buff = self.line_to_number_buff if buff is None else buff 

1274 font_size = self.font_size if font_size is None else font_size 

1275 if label_constructor is None: 

1276 label_constructor = self.label_constructor 

1277 labels = VGroup() 

1278 for x, label in dict_values.items(): 

1279 if isinstance(label, str): 

1280 if label_constructor is MathTex: 

1281 label = Tex(label) 

1282 else: 

1283 label = self._create_label_tex(label, label_constructor) 

1284 else: 

1285 label = self._create_label_tex(label, label_constructor) 

1286 if not isinstance( 

1287 label, (Typst, DecimalNumber) 

1288 ): # its type size can be set 

1289 raise AttributeError(f"{label} is not compatible with add_labels.") 

1290 label.font_size = font_size 

1291 label.next_to(self.number_to_point(x), direction=direction, buff=buff) 

1292 labels.add(label) 

1293 self.labels = labels 

1294 self.add(labels) 

1295 return self 

1296 

1297 def _create_label_tex( 

1298 self, 

1299 label_tex: Label, 

1300 label_constructor: type[ManimTextLabel] | None = None, 

1301 **kwargs: Unpack[Style], 

1302 ) -> Mobject: 

1303 if isinstance(label_tex, Mobject): 

1304 return label_tex 

1305 if label_constructor is None: 

1306 label_constructor = self.label_constructor 

1307 if isinstance(label_tex, str): 

1308 return label_constructor(label_tex, **kwargs) 

1309 return label_constructor(str(label_tex), **kwargs) 

1310 

1311 @staticmethod 

1312 def _decimal_places_of(value: float) -> int: 

1313 """The decimal places a number is written with, to 15 significant digits. 

1314 

1315 Fifteen digits leave out a float's round-off (0.1 + 0.2 has one place) and 

1316 read an exponent (1e-05 has five); a whole number has none. 

1317 

1318 Args: 

1319 value: The number. 

1320 

1321 Returns: 

1322 How many decimal places it has. 

1323 """ 

1324 mantissa, _, exponent = f"{value:.15g}".partition("e") 

1325 return max(0, len(mantissa.partition(".")[2]) - int(exponent or 0)) 

1326 

1327 

1328class UnitInterval(NumberLine): 

1329 """The unit interval: a number line from 0 to 1, with a tick every tenth; 10 units 

1330 long, its ticks at 0 and 1 longer, unless told otherwise. 

1331 

1332 Its numbers, when it has them, have one decimal place. 

1333 

1334 Args: 

1335 **kwargs: [Number line keywords][manimgx.NumberLine]: 

1336 its range is always `[0, 1, 0.1]`, and its `unit_size`, 

1337 `numbers_with_elongated_ticks` and `decimal_number_config` default to 10, 

1338 [0, 1] and one decimal place. 

1339 

1340 Examples: 

1341 ```python 

1342 import manimgx as m 

1343 

1344 

1345 class UnitIntervalExample(m.Scene): 

1346 def construct(self) -> None: 

1347 interval = m.UnitInterval(include_numbers=True, font_size=28) 

1348 dot = m.Dot(interval.n2p(0.25), radius=0.12, color=m.YELLOW) 

1349 self.add(interval, dot) 

1350 self.play(dot.animate.move_to(interval.n2p(0.8))) 

1351 ``` 

1352 """ 

1353 

1354 def __init__(self, **kwargs: Unpack[NumberLineOptions]): 

1355 kwargs.setdefault("unit_size", 10) 

1356 kwargs.setdefault("numbers_with_elongated_ticks", [0, 1]) 

1357 kwargs.setdefault("decimal_number_config", {"num_decimal_places": 1}) 

1358 super().__init__(x_range=(0, 1, 0.1), **kwargs) 

1359 

1360 

1361type Coordinates = ( 

1362 float | Sequence[float] | np.ndarray 

1363) # a number per axis, or arrays of them 

1364 

1365 

1366"""A coordinate on one axis: a number, or an array of numbers (of any shape) for many 

1367points at once.""" 

1368 

1369 

1370def _halved(opacity: float | Sequence[float]) -> float | list[float]: 

1371 """An opacity, or one for each part, at half strength.""" 

1372 if isinstance(opacity, int | float): 

1373 return opacity * 0.5 

1374 return [o * 0.5 for o in opacity] 

1375 

1376 

1377def merged_axis_config(*configs: NumberLineOptions | None) -> NumberLineOptions: 

1378 """Merge axis configs: later ones win, key by key, and inside their 

1379 `decimal_number_config` too. An iterator among the values is read into a list: the 

1380 config is shared by every axis, and an iterator would give its numbers to the first. 

1381 

1382 Args: 

1383 *configs: [Number line keywords][manimgx.NumberLine], 

1384 in order; None for none. 

1385 

1386 Returns: 

1387 A new config. 

1388 """ 

1389 merged: NumberLineOptions = {} 

1390 for config_ in configs: 

1391 if config_: 

1392 numbers = ( 

1393 merged.get("decimal_number_config") or DecimalNumberOptions() 

1394 ) | (config_.get("decimal_number_config") or DecimalNumberOptions()) 

1395 merged = merged | config_ 

1396 if numbers: 

1397 merged["decimal_number_config"] = numbers 

1398 for key in ( 

1399 "numbers_to_include", 

1400 "numbers_to_exclude", 

1401 "numbers_with_elongated_ticks", 

1402 ): 

1403 values = merged.get(key) 

1404 if isinstance(values, Iterator): 

1405 merged[key] = list(values) 

1406 return merged 

1407 

1408 

1409class AxisLine(TypedDict, total=False, closed=True): 

1410 """The keywords of a line from an axis to a point 

1411 ([get_vertical_line][manimgx.Axes.get_vertical_line] and the like): its class, its 

1412 keywords, its color and its width.""" 

1413 

1414 line_func: type[Line] 

1415 """The class of the line (default [DashedLine][manimgx.DashedLine]; a 

1416 [Line][manimgx.Line] is solid).""" 

1417 line_config: DashedLineOptions | None 

1418 """[Dashed line keywords][manimgx.DashedLine] for the 

1419 line, but its color and width, which `color` and `stroke_width` set (default None: 

1420 none).""" 

1421 color: ParsableManimColor | None 

1422 """The line's color (default None: white).""" 

1423 stroke_width: float 

1424 """The line's width, in hundredths of a scene unit (default 2).""" 

1425 

1426 

1427class PlotOptions(_CurveOptions, total=False, closed=True): 

1428 """[plot][manimgx.Axes.plot]'s keywords but its function, for the methods that pass 

1429 them on ([plot_derivative_graph][manimgx.Axes.plot_derivative_graph], 

1430 [plot_antiderivative_graph][manimgx.Axes.plot_antiderivative_graph]): the range of 

1431 x and the colorscale, with the curve keywords.""" 

1432 

1433 x_range: Sequence[float] | None 

1434 """The range of x the graph spans, `[x_min, x_max]` or `[x_min, x_max, x_step]`, 

1435 the function sampled every `x_step` (default None: the x-axis's range; without a 

1436 step, a tenth of the x-axis's).""" 

1437 use_vectorized: bool 

1438 """Whether the function takes all the values of x at once, as an array (default 

1439 False: it is tried on an array anyway, and called once per value if it does not 

1440 take one).""" 

1441 colorscale: Colorscale | None 

1442 """Colors to paint the graph with by its value: colors spread evenly over the 

1443 axis's range, or `(color, value)` pairs, blended between (default None: the 

1444 graph's own color).""" 

1445 colorscale_axis: int 

1446 """The value the colorscale goes by: 1 for y, 0 for x (default 1).""" 

1447 

1448 

1449class SecantSlopeGroup(VGroup): 

1450 """A secant's construction, as 

1451 [get_secant_slope_group][manimgx.Axes.get_secant_slope_group] makes it: its dx and 

1452 df legs, their labels and the secant line, each by name.""" 

1453 

1454 dx_line: Line 

1455 """The horizontal leg: from the first point of the graph across to below (or 

1456 above) the second.""" 

1457 df_line: Line 

1458 """The vertical leg: from the end of `dx_line` to the second point.""" 

1459 dx_label: Mobject 

1460 """The horizontal leg's label, if it has one.""" 

1461 df_label: Mobject 

1462 """The vertical leg's label, if it has one.""" 

1463 secant_line: Line 

1464 """The secant: the line through both points, if it has one.""" 

1465 

1466 

1467class Axes(VGroup): 

1468 """Axes: number lines through one origin, with coordinates of their own, and the 

1469 tools to plot on them; white, with tips, unless configured. 

1470 

1471 Axis option maps are construction inputs. The finished number lines 

1472 retain their own defaults for later ticks, labels and coordinates. 

1473 

1474 The x-axis runs over `x_range` and the y-axis over `y_range`, each a 

1475 [NumberLine][manimgx.NumberLine] with ticks at every step of its range. The axes 

1476 cross at their 0 (or, for a range without 0, at its end nearest 0), and the point 

1477 of the middle of both ranges is put at the scene's origin. On a linear axis the 

1478 tick at 0 is left out, where the other axis crosses; numbers are written at the 

1479 ticks but 0 (see [add_coordinates][manimgx.Axes.add_coordinates]). 

1480 

1481 [coords_to_point][manimgx.Axes.coords_to_point] (`c2p`, or `axes @ (x, y)`) and 

1482 [point_to_coords][manimgx.Axes.point_to_coords] (`p2c`) convert between the axes' 

1483 coordinates and the scene's points. The `plot` methods draw on the axes, in their 

1484 coordinates: graphs of functions, curves given implicitly or in polar coordinates, 

1485 line graphs. The `get_` methods make what explains a graph: its label, the area 

1486 under it, Riemann rectangles, a secant, lines to a point. All of them return new 

1487 mobjects, not added to the axes. 

1488 

1489 Args: 

1490 x_range: The x-axis's range, `[x_min, x_max, x_step]`, or `[x_min, x_max]` for 

1491 a step of 1; None for the frame's width, [-7, 7, 1]. 

1492 y_range: The y-axis's range, likewise; None for the frame's height, [-4, 4, 1]. 

1493 x_length: The x-axis's length, in scene units; None for the frame's width 

1494 less 2, rounded, as the frame is when the axes are made (12 in a wide video, 

1495 6 in a tall one), or `unit_size` per unit if the axis's config gives one. 

1496 y_length: The y-axis's length, in scene units; None for the frame's height 

1497 less 2, rounded (6 in a wide video, 12 in a tall one), or `unit_size` per unit 

1498 if the axis's config gives one. 

1499 axis_config: [Number line keywords][manimgx.NumberLine] 

1500 for both axes: `include_numbers`, `font_size`, `color`, …; None for none. 

1501 x_axis_config: Number line keywords for the x-axis, over `axis_config`'s; None 

1502 for none. 

1503 y_axis_config: Number line keywords for the y-axis, over `axis_config`'s; None 

1504 for none. 

1505 tips: Whether each axis ends in an arrow tip. 

1506 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the axes' group itself: 

1507 as it has no points, they do not restyle the axes (`axis_config` does). 

1508 

1509 Examples: 

1510 ```python 

1511 import manimgx as m 

1512 

1513 

1514 class AxesExample(m.Scene): 

1515 def construct(self) -> None: 

1516 axes = m.Axes( 

1517 x_range=[0, 10, 1], 

1518 y_range=[-2, 6, 2], 

1519 x_length=10, 

1520 y_length=6, 

1521 axis_config={"include_numbers": True, "font_size": 28}, 

1522 ) 

1523 labels = axes.get_axis_labels("t", "v") 

1524 graph = axes.plot(lambda t: 5 - 0.2 * (t - 4) ** 2, color=m.BLUE) 

1525 self.add(axes, labels) 

1526 self.play(m.Create(graph)) 

1527 ``` 

1528 """ 

1529 

1530 def __init__( 

1531 self, 

1532 x_range: Sequence[float] | None = None, 

1533 y_range: Sequence[float] | None = None, 

1534 x_length: float | None = None, 

1535 y_length: float | None = None, 

1536 axis_config: NumberLineOptions | None = None, 

1537 x_axis_config: NumberLineOptions | None = None, 

1538 y_axis_config: NumberLineOptions | None = None, 

1539 tips: bool = True, 

1540 **kwargs: Unpack[Style], 

1541 ): 

1542 super().__init__(**kwargs) 

1543 self.dimension = 2 

1544 self.x_range = _full_range(x_range, config.frame_x_radius) 

1545 """The x-axis's range, `[x_min, x_max, x_step]`.""" 

1546 self.y_range = _full_range(y_range, config.frame_y_radius) 

1547 """The y-axis's range, `[y_min, y_max, y_step]`.""" 

1548 self.num_sampled_graph_points_per_tick = 10 

1549 """How many times per step of the x-axis [plot][manimgx.Axes.plot] samples a 

1550 function, when not given a step (default 10).""" 

1551 axis_config = merged_axis_config( 

1552 {"include_tip": tips, "numbers_to_exclude": [0]}, axis_config 

1553 ) 

1554 x_axis_config = _origin_tick(merged_axis_config(axis_config, x_axis_config)) 

1555 y_axis_config = _origin_tick( 

1556 merged_axis_config( 

1557 axis_config, 

1558 {"rotation": 90 * DEGREES, "label_direction": LEFT}, 

1559 y_axis_config, 

1560 ) 

1561 ) 

1562 self.x_axis = self._create_axis(self.x_range, x_axis_config, x_length, 0) 

1563 """The x-axis, a [NumberLine][manimgx.NumberLine].""" 

1564 self.y_axis = self._create_axis(self.y_range, y_axis_config, y_length, 1) 

1565 """The y-axis, a [NumberLine][manimgx.NumberLine].""" 

1566 self.x_length, self.y_length = ( 

1567 self.x_axis.get_length(), 

1568 self.y_axis.get_length(), 

1569 ) 

1570 self.axes = Group[NumberLine](self.x_axis, self.y_axis) 

1571 """The axes, in a group: the x-axis, the y-axis (and the z-axis, in 3D).""" 

1572 self.add(*self.axes) 

1573 lines_center_point = [ 

1574 axis.scaling.function((axis.x_range[1] + axis.x_range[0]) / 2) 

1575 for axis in self.axes 

1576 ] 

1577 self.shift(-self.coords_to_point(*lines_center_point)) 

1578 

1579 def _create_axis( 

1580 self, 

1581 range_terms: Sequence[float] | None, 

1582 axis_config: NumberLineOptions, 

1583 length: float | None, 

1584 index: int, 

1585 ) -> NumberLine: 

1586 if length is None and "unit_size" not in axis_config: 

1587 length = self._fitting_length(index) 

1588 axis = NumberLine(range_terms, **(axis_config | {"length": length})) 

1589 axis.shift(-axis.number_to_point(_origin_shift([axis.x_min, axis.x_max]))) 

1590 return axis 

1591 

1592 def _fitting_length(self, index: int) -> float: 

1593 """The length of an axis given none (0: x, 1: y): the frame's width or height 

1594 less 2, rounded, as the frame is now (a scene's file may make it tall after 

1595 ManimGX is imported).""" 

1596 return round((config.frame_width, config.frame_height)[index]) - 2 

1597 

1598 def coords_to_point(self, *coords: Coordinates) -> npt.NDArray[np.float64]: 

1599 """Convert coordinates on the axes to a point of the scene, or arrays of them to 

1600 points. 

1601 

1602 `c2p` is its short name, and `axes @ (x, y)` its shortest. Coordinates past the 

1603 ends of the axes are on the axes extended; a missing one is where the axes 

1604 cross (`c2p(x)` is on the x-axis). Given an array per axis, of any shape (a 

1605 grid too), it converts them all at once. 

1606 

1607 Args: 

1608 *coords: The coordinates, one per axis, in order: numbers, or arrays of one 

1609 shape. 

1610 

1611 Returns: 

1612 The point, in scene coordinates; for arrays, the points, with the 

1613 coordinates first (3, then the arrays' shape). 

1614 

1615 Examples: 

1616 ```python 

1617 import manimgx as m 

1618 

1619 

1620 class AxesCoordsToPointExample(m.Scene): 

1621 def construct(self) -> None: 

1622 axes = m.Axes( 

1623 x_range=[0, 6], y_range=[0, 4], x_length=10, y_length=6 

1624 ) 

1625 dot = m.Dot(axes.c2p(1, 1), radius=0.15, color=m.YELLOW) 

1626 self.add(axes.add_coordinates(), dot) 

1627 self.play(dot.animate.move_to(axes.c2p(5, 3))) 

1628 self.play(dot.animate.move_to(axes @ (3, 0.5))) 

1629 ``` 

1630 """ 

1631 origin = self.x_axis.number_to_point( 

1632 _origin_shift([self.x_axis.x_min, self.x_axis.x_max]) 

1633 ) 

1634 points = self.x_axis.number_to_point(np.asarray(coords[0], dtype=float)) 

1635 for axis, nums in zip(self.axes.submobjects[1:], coords[1:], strict=False): 

1636 points = ( 

1637 points + axis.number_to_point(np.asarray(nums, dtype=float)) - origin 

1638 ) 

1639 return points if points.ndim == 1 else np.moveaxis(points, -1, 0) 

1640 

1641 def point_to_coords( 

1642 self, point: Point3DLike | Point3DLike_Array 

1643 ) -> npt.NDArray[np.float64]: 

1644 """Convert a point of the scene to its coordinates on the axes, or points to 

1645 theirs. 

1646 

1647 `p2c` is its short name. Each coordinate is the axis's number at the point's 

1648 projection onto it: for perpendicular axes, the inverse of 

1649 [coords_to_point][manimgx.Axes.coords_to_point]. 

1650 

1651 Args: 

1652 point: The point, in scene coordinates; or an (n, 3) array of points. 

1653 

1654 Returns: 

1655 The coordinates, one per axis; for n points, an array of n rows of them. 

1656 """ 

1657 array = np.asarray(point, dtype=float) 

1658 result = np.asarray([axis.point_to_number(array) for axis in self.axes]) 

1659 return result.T if array.ndim == 2 else result 

1660 

1661 def polar_to_point(self, radius: float, azimuth: float) -> npt.NDArray[np.float64]: 

1662 """Convert polar coordinates on the axes to a point of the scene. 

1663 

1664 `pr2pt` is its short name. The point is at the coordinates 

1665 (`radius` cos `azimuth`, `radius` sin `azimuth`). 

1666 

1667 Args: 

1668 radius: The distance from the origin, in the axes' units. 

1669 azimuth: The angle from the positive x-axis, in radians, counterclockwise. 

1670 

1671 Returns: 

1672 The point, in scene coordinates. 

1673 """ 

1674 return self.coords_to_point(radius * np.cos(azimuth), radius * np.sin(azimuth)) 

1675 

1676 c2p, p2c, pr2pt = coords_to_point, point_to_coords, polar_to_point 

1677 

1678 def get_axes(self) -> Group[NumberLine]: 

1679 """The axes: the x-axis, the y-axis (and the z-axis, in 3D). 

1680 

1681 Returns: 

1682 The group of the axes, each a [NumberLine][manimgx.NumberLine]. 

1683 """ 

1684 return self.axes 

1685 

1686 def get_axis(self, index: int) -> NumberLine: 

1687 """One of the axes. 

1688 

1689 Args: 

1690 index: The axis's index: 0 for x, 1 for y, 2 for z. 

1691 

1692 Returns: 

1693 The axis, a [NumberLine][manimgx.NumberLine]. 

1694 """ 

1695 return self.get_axes()[index] 

1696 

1697 def get_origin(self) -> Point3D: 

1698 """The point of the coordinates (0, 0): where the axes cross, if their ranges 

1699 contain 0. 

1700 

1701 Returns: 

1702 The point, in scene coordinates. 

1703 """ 

1704 return self.coords_to_point(0, 0) 

1705 

1706 def get_x_axis(self) -> NumberLine: 

1707 """The x-axis. 

1708 

1709 Returns: 

1710 The axis, a [NumberLine][manimgx.NumberLine]. 

1711 """ 

1712 return self.get_axis(0) 

1713 

1714 def get_y_axis(self) -> NumberLine: 

1715 """The y-axis. 

1716 

1717 Returns: 

1718 The axis, a [NumberLine][manimgx.NumberLine]. 

1719 """ 

1720 return self.get_axis(1) 

1721 

1722 def get_z_axis(self) -> NumberLine: 

1723 """The z-axis, of three-dimensional axes. 

1724 

1725 Returns: 

1726 The axis, a [NumberLine][manimgx.NumberLine]. 

1727 """ 

1728 return self.get_axis(2) 

1729 

1730 def get_x_unit_size(self) -> float: 

1731 """The length of one unit of the x-axis. 

1732 

1733 Returns: 

1734 The length, in scene units. 

1735 """ 

1736 return self.get_x_axis().get_unit_size() 

1737 

1738 def get_y_unit_size(self) -> float: 

1739 """The length of one unit of the y-axis. 

1740 

1741 Returns: 

1742 The length, in scene units. 

1743 """ 

1744 return self.get_y_axis().get_unit_size() 

1745 

1746 def get_x_axis_label( 

1747 self, 

1748 label: Label, 

1749 edge: Vector3DLike = UR, 

1750 direction: Vector3DLike = UR, 

1751 buff: float = SMALL_BUFF, 

1752 ) -> Mobject: 

1753 """Make a label for the x-axis, by its end. 

1754 

1755 A string or a number is typeset with the axes' `label_constructor` (as math, 

1756 with [MathTex][manimgx.MathTex], by default); a mobject is used as it is. The 

1757 label is put next to a corner of the axis, toward `direction`, then moved onto 

1758 the screen if it is off it. 

1759 

1760 Args: 

1761 label: The label: a string, a number or a mobject. 

1762 edge: The corner of the axis the label is put by, as a direction: UR, the 

1763 upper right one, by its end. 

1764 direction: The direction the label is put toward, from that corner. 

1765 buff: The gap between the corner and the label, in scene units. 

1766 

1767 Returns: 

1768 The label, not added to the axes. 

1769 """ 

1770 return self._get_axis_label( 

1771 label, self.get_x_axis(), edge, direction, buff=buff 

1772 ) 

1773 

1774 def get_y_axis_label( 

1775 self, 

1776 label: Label, 

1777 edge: Vector3DLike = UR, 

1778 direction: Vector3DLike = UP * 0.5 + RIGHT, 

1779 buff: float = SMALL_BUFF, 

1780 ) -> Mobject: 

1781 """Make a label for the y-axis, by its end. 

1782 

1783 A string or a number is typeset with the axes' `label_constructor` (as math, 

1784 with [MathTex][manimgx.MathTex], by default); a mobject is used as it is. The 

1785 label is put next to a corner of the axis, toward `direction`, then moved onto 

1786 the screen if it is off it. 

1787 

1788 Args: 

1789 label: The label: a string, a number or a mobject. 

1790 edge: The corner of the axis the label is put by, as a direction: UR, the 

1791 upper right one, by its end. 

1792 direction: The direction the label is put toward, from that corner: by 

1793 default up and to the right. 

1794 buff: The gap between the corner and the label, in scene units. 

1795 

1796 Returns: 

1797 The label, not added to the axes. 

1798 """ 

1799 return self._get_axis_label( 

1800 label, self.get_y_axis(), edge, direction, buff=buff 

1801 ) 

1802 

1803 def _get_axis_label( 

1804 self, 

1805 label: Label, 

1806 axis: Mobject, 

1807 edge: Vector3DLike, 

1808 direction: Vector3DLike, 

1809 buff: float = SMALL_BUFF, 

1810 ) -> Mobject: 

1811 label_mobject: Mobject = self.x_axis._create_label_tex(label) 

1812 label_mobject.next_to( 

1813 axis.get_critical_point(edge), direction=direction, buff=buff 

1814 ) 

1815 label_mobject.shift_onto_screen(buff=MED_SMALL_BUFF) 

1816 return label_mobject 

1817 

1818 def get_axis_labels(self, x_label: Label = "x", y_label: Label = "y") -> VGroup: 

1819 """Make a label for each axis, by its end, as 

1820 [get_x_axis_label][manimgx.Axes.get_x_axis_label] and 

1821 [get_y_axis_label][manimgx.Axes.get_y_axis_label] place them. 

1822 

1823 Args: 

1824 x_label: The x-axis's label: a string or a number, typeset as math, or a 

1825 mobject. 

1826 y_label: The y-axis's label, likewise. 

1827 

1828 Returns: 

1829 A new group of the labels, kept as the axes' `axis_labels`; not added to 

1830 the axes. 

1831 

1832 Examples: 

1833 ```python 

1834 import manimgx as m 

1835 

1836 

1837 class AxesGetAxisLabelsExample(m.Scene): 

1838 def construct(self) -> None: 

1839 axes = m.Axes(x_range=[0, 10], y_range=[0, 5], x_length=10) 

1840 labels = axes.get_axis_labels(m.Tex("time"), m.Tex("height")) 

1841 self.add(axes, labels) 

1842 ``` 

1843 """ 

1844 self.axis_labels = VGroup( 

1845 self.get_x_axis_label(x_label), self.get_y_axis_label(y_label) 

1846 ) 

1847 return self.axis_labels 

1848 

1849 def add_coordinates( 

1850 self, 

1851 *axes_numbers: Iterable[float] | Mapping[float, Label] | None, 

1852 **kwargs: Unpack[DecimalNumberOptions], 

1853 ) -> Self: 

1854 """Number the axes: at their ticks, at the values given, or with labels by 

1855 value. 

1856 

1857 Give one argument per axis, in order: None numbers the axis at its ticks, but 

1858 0 (on a logarithmic axis, as powers: 10², 10³, …); values number it at those 

1859 values; a dictionary from values to labels (strings, numbers or typeset 

1860 mobjects) puts each label by its value (see 

1861 [add_labels][manimgx.NumberLine.add_labels]). Without arguments, every axis is 

1862 numbered at its ticks. The numbers are added to the axes, and kept, one group 

1863 per axis, as the axes' `coordinate_labels`. 

1864 

1865 Args: 

1866 *axes_numbers: What to write on each axis, in order: None, values, or 

1867 labels by value; the axes past the last argument get nothing. 

1868 **kwargs: [Number keywords][manimgx.DecimalNumber] 

1869 for the numbers: `font_size`, `num_decimal_places`, `color`, … (only 

1870 `font_size`, for labels by value). 

1871 

1872 Examples: 

1873 ```python 

1874 import manimgx as m 

1875 

1876 

1877 class AxesAddCoordinatesExample(m.Scene): 

1878 def construct(self) -> None: 

1879 axes = m.Axes( 

1880 x_range=[0, 5], y_range=[0, 1, 0.25], x_length=10, y_length=6 

1881 ) 

1882 axes.add_coordinates( 

1883 {1: "one", 2: "two", 3: "three", 4: "four"}, None, font_size=30 

1884 ) 

1885 self.add(axes) 

1886 ``` 

1887 """ 

1888 self.coordinate_labels = VGroup() 

1889 for axis, values in zip( 

1890 self.axes, axes_numbers or (None,) * self.dimension, strict=False 

1891 ): 

1892 if isinstance(values, Mapping): 

1893 axis.add_labels(values, font_size=kwargs.get("font_size")) 

1894 labels = axis.labels 

1895 elif values is None and axis.scaling.custom_labels: 

1896 tick_range = axis.get_tick_range() 

1897 axis.add_labels( 

1898 dict( 

1899 zip( 

1900 tick_range, 

1901 axis.scaling.get_custom_labels(tick_range), 

1902 strict=True, 

1903 ) 

1904 ) 

1905 ) 

1906 labels = axis.labels 

1907 else: 

1908 axis.add_numbers(values, **kwargs) 

1909 labels = axis.numbers 

1910 self.coordinate_labels.add(labels) 

1911 return self 

1912 

1913 @deprecated("use get_vertical_line or get_horizontal_line", category=None) 

1914 def get_line_from_axis_to_point( 

1915 self, 

1916 index: int, 

1917 point: Point3DLike, 

1918 line_func: type[Line] = DashedLine, 

1919 line_config: DashedLineOptions | None = None, 

1920 color: ParsableManimColor | None = None, 

1921 stroke_width: float = 2, 

1922 ) -> Line: 

1923 """Make a line from an axis to a point: from the point's projection onto the 

1924 axis, dashed, white and thin unless styled. 

1925 

1926 Args: 

1927 index: The axis's index: 0 for x, 1 for y. 

1928 point: The point, in scene coordinates. 

1929 line_func: The class of the line: [DashedLine][manimgx.DashedLine], or 

1930 [Line][manimgx.Line] for a solid one, …. 

1931 line_config: [Dashed line keywords][manimgx.DashedLine] 

1932 for the line, but its color and width; None for none. 

1933 color: The line's color; None for white. 

1934 stroke_width: The line's width, in hundredths of a scene unit. 

1935 

1936 Returns: 

1937 A new line, not added to the axes. 

1938 """ 

1939 start = self.get_axis(index).get_projection(point) 

1940 style = (line_config or DashedLineOptions()).copy() 

1941 style["color"], style["stroke_width"] = ( 

1942 ManimColor(WHITE if color is None else color), 

1943 stroke_width, 

1944 ) 

1945 if issubclass(line_func, DashedLine): 

1946 return line_func(start, point, **style) 

1947 # a solid line has no dashes: it takes the line keywords without them 

1948 style.pop("dash_length", None) 

1949 style.pop("dashed_ratio", None) 

1950 return line_func(start, point, **cast("LineOptions", style)) 

1951 

1952 def get_vertical_line(self, point: Point3DLike, **kwargs: Unpack[AxisLine]) -> Line: 

1953 """Make a line from the x-axis up (or down) to a point: dashed, white and thin 

1954 unless styled. 

1955 

1956 Args: 

1957 point: The point, in scene coordinates. 

1958 **kwargs: [Axis line keywords][manimgx.mobjects.plotting.AxisLine]: 

1959 the line's class, keywords, `color` and `stroke_width`. 

1960 

1961 Returns: 

1962 A new line, not added to the axes. 

1963 """ 

1964 return self.get_line_from_axis_to_point(0, point, **kwargs) 

1965 

1966 def get_horizontal_line( 

1967 self, point: Point3DLike, **kwargs: Unpack[AxisLine] 

1968 ) -> Line: 

1969 """Make a line from the y-axis across to a point: dashed, white and thin unless 

1970 styled. 

1971 

1972 Args: 

1973 point: The point, in scene coordinates. 

1974 **kwargs: [Axis line keywords][manimgx.mobjects.plotting.AxisLine]: 

1975 the line's class, keywords, `color` and `stroke_width`. 

1976 

1977 Returns: 

1978 A new line, not added to the axes. 

1979 """ 

1980 return self.get_line_from_axis_to_point(1, point, **kwargs) 

1981 

1982 def get_lines_to_point( 

1983 self, point: Point3DLike, **kwargs: Unpack[AxisLine] 

1984 ) -> VGroup: 

1985 """Make the lines from both axes to a point: the 

1986 [horizontal][manimgx.Axes.get_horizontal_line] one from the y-axis, then the 

1987 [vertical][manimgx.Axes.get_vertical_line] one from the x-axis. 

1988 

1989 Args: 

1990 point: The point, in scene coordinates. 

1991 **kwargs: [Axis line keywords][manimgx.mobjects.plotting.AxisLine] 

1992 for both lines. 

1993 

1994 Returns: 

1995 A new group of the two lines, not added to the axes. 

1996 

1997 Examples: 

1998 ```python 

1999 import manimgx as m 

2000 

2001 

2002 class AxesGetLinesToPointExample(m.Scene): 

2003 def construct(self) -> None: 

2004 axes = m.Axes(x_range=[0, 6], y_range=[0, 4], x_length=10) 

2005 dot = m.Dot(axes.c2p(4, 3), radius=0.15, color=m.YELLOW) 

2006 lines = axes.get_lines_to_point(dot.get_center(), color=m.BLUE) 

2007 self.add(axes.add_coordinates(), dot) 

2008 self.play(m.Create(lines)) 

2009 ``` 

2010 """ 

2011 return VGroup( 

2012 self.get_horizontal_line(point, **kwargs), 

2013 self.get_vertical_line(point, **kwargs), 

2014 ) 

2015 

2016 def plot( 

2017 self, 

2018 function: Callable[[float], float], 

2019 x_range: Sequence[float] | None = None, 

2020 use_vectorized: bool = False, 

2021 colorscale: Colorscale | None = None, 

2022 colorscale_axis: int = 1, 

2023 **kwargs: Unpack[CurveOptions], 

2024 ) -> ParametricFunction: 

2025 """Plot the graph of a function y = f(x) on the axes, in their coordinates. 

2026 

2027 The function is sampled over `x_range` and the samples are joined smoothly (see 

2028 [ParametricFunction][manimgx.ParametricFunction]); on a logarithmic x-axis, x 

2029 runs over powers. The graph keeps the function as its `underlying_function`, 

2030 for the methods that work on graphs. With a `colorscale`, the graph's stroke is 

2031 a gradient, from left to right, of the colors of its values (y, or x), taken at 

2032 every step of `x_range` (every 0.01 without one). 

2033 

2034 Args: 

2035 function: The function, from x to y, in the axes' coordinates. 

2036 x_range: The range of x the graph spans, `[x_min, x_max]` or 

2037 `[x_min, x_max, x_step]`, the function sampled every `x_step`; None 

2038 for the x-axis's range. Without a step, it is a tenth of the x-axis's. 

2039 use_vectorized: Whether `function` takes all the values of x at once, as an 

2040 array; it is tried on an array anyway, and called once per value if it 

2041 does not take one. 

2042 colorscale: Colors to paint the graph with by its value: colors spread 

2043 evenly over the axis's range, or `(color, value)` pairs, blended 

2044 between; None for the graph's own color. 

2045 colorscale_axis: The value the colorscale goes by: 1 for y, 0 for x. 

2046 **kwargs: [Curve keywords][manimgx.mobjects.plotting.CurveOptions]: 

2047 `discontinuities`, `use_smoothing`, and the style keywords. 

2048 

2049 Returns: 

2050 A new [ParametricFunction][manimgx.ParametricFunction], not added to the 

2051 axes. 

2052 

2053 Examples: 

2054 ```python 

2055 import numpy as np 

2056 

2057 import manimgx as m 

2058 

2059 

2060 class AxesPlotExample(m.Scene): 

2061 def construct(self) -> None: 

2062 axes = m.Axes(x_range=[-4, 4], y_range=[-2, 2], y_length=6) 

2063 sine = axes.plot(np.sin, color=m.BLUE) 

2064 parabola = axes.plot( 

2065 lambda x: x**2 - 1.5, 

2066 x_range=[-1.8, 1.8], 

2067 colorscale=[m.GREEN, m.YELLOW, m.RED], 

2068 ) 

2069 self.add(axes) 

2070 self.play(m.Create(sine), m.Create(parabola)) 

2071 ``` 

2072 """ 

2073 t_range = np.array(self.x_range, dtype=float) 

2074 if x_range is not None: 

2075 t_range[: len(x_range)] = x_range 

2076 if x_range is None or len(x_range) < 3: 

2077 t_range[2] /= self.num_sampled_graph_points_per_tick 

2078 

2079 def point(t: float | np.ndarray) -> np.ndarray: 

2080 """The graph's point at t — or at every t of an array, mapped in one call.""" 

2081 if isinstance(t, np.ndarray): 

2082 return self.coords_to_point(t, sample(function, t)) 

2083 return self.coords_to_point(t, function(t)) 

2084 

2085 graph = ParametricFunction( 

2086 point, 

2087 t_range=t_range, 

2088 scaling=self.x_axis.scaling, 

2089 use_vectorized=use_vectorized, 

2090 **kwargs, 

2091 ) 

2092 graph.underlying_function = function 

2093 if colorscale: 

2094 resolution = ( 

2095 x_range[2] if x_range is not None and len(x_range) == 3 else 0.01 

2096 ) 

2097 graph.set_stroke( 

2098 self._colorscale( 

2099 function, colorscale, colorscale_axis, t_range, resolution 

2100 ) 

2101 ) 

2102 graph.set_sheen_direction(RIGHT) 

2103 return graph 

2104 

2105 def _colorscale( 

2106 self, 

2107 function: Callable[[float], float], 

2108 colorscale: Colorscale, 

2109 axis: int, 

2110 t_range: np.ndarray, 

2111 resolution: float, 

2112 ) -> list[ManimColor]: 

2113 """Colors along a graph by its x or y value (`axis`), over that axis' range by default.""" 

2114 low, high = (self.x_range, self.y_range)[axis][:2] 

2115 xs = np.arange(t_range[0], t_range[1] + resolution, resolution) 

2116 return colors_by_value( 

2117 colorscale, ((x, function(x))[axis] for x in xs), low, high 

2118 ) 

2119 

2120 def plot_implicit_curve( 

2121 self, 

2122 func: Callable[[float, float], float], 

2123 min_depth: int = 5, 

2124 max_quads: int = 1500, 

2125 **kwargs: Unpack[ImplicitOptions], 

2126 ) -> ImplicitFunction: 

2127 """Plot the curve where a function of x and y is zero, `func(x, y) = 0`, on the 

2128 axes, in their coordinates: found within their ranges. 

2129 

2130 The rectangle of the ranges is divided in four, and each part in four again, 

2131 finer where the curve passes (see [ImplicitFunction][manimgx.ImplicitFunction]). 

2132 On a logarithmic axis, the function is given powers. 

2133 

2134 Args: 

2135 func: The function of x and y, in the axes' coordinates. 

2136 min_depth: How many times the rectangle is at least divided in four: more 

2137 finds smaller pieces of the curve. 

2138 max_quads: The most cells the rectangle may be divided into: more follow 

2139 the curve more closely, and take longer. 

2140 **kwargs: [Implicit curve keywords][manimgx.mobjects.plotting.ImplicitOptions]: 

2141 `use_smoothing`, and the style keywords. 

2142 

2143 Returns: 

2144 A new [ImplicitFunction][manimgx.ImplicitFunction], not added to the axes. 

2145 

2146 Examples: 

2147 ```python 

2148 import manimgx as m 

2149 

2150 

2151 class AxesPlotImplicitCurveExample(m.Scene): 

2152 def construct(self) -> None: 

2153 axes = m.Axes(x_range=[-3, 3], y_range=[-3, 3], y_length=7) 

2154 curve = axes.plot_implicit_curve( 

2155 lambda x, y: y**2 - x**3 + 2 * x - 1, color=m.YELLOW 

2156 ) 

2157 self.add(axes) 

2158 self.play(m.Create(curve)) 

2159 ``` 

2160 """ 

2161 x_scale = self.get_x_axis().scaling 

2162 y_scale = self.get_y_axis().scaling 

2163 graph = ImplicitFunction( 

2164 func=lambda x, y: func(x_scale.function(x), y_scale.function(y)), 

2165 x_range=self.x_range[:2], 

2166 y_range=self.y_range[:2], 

2167 min_depth=min_depth, 

2168 max_quads=max_quads, 

2169 **kwargs, 

2170 ) 

2171 graph.stretch(self.get_x_unit_size(), 0, about_point=ORIGIN).stretch( 

2172 self.get_y_unit_size(), 1, about_point=ORIGIN 

2173 ).shift(self.get_origin()) 

2174 return graph 

2175 

2176 def plot_polar_graph( 

2177 self, 

2178 r_func: Callable[[float], float], 

2179 theta_range: Sequence[float] | None = None, 

2180 **kwargs: Unpack[CurveOptions], 

2181 ) -> ParametricFunction: 

2182 """Plot a curve in polar coordinates, r = r_func(θ), on the axes: for each 

2183 angle θ of its range, the point in the direction θ from the origin, at the 

2184 distance `r_func(θ)`. 

2185 

2186 Args: 

2187 r_func: The function, from the angle θ, in radians, to the distance r, in 

2188 the axes' units. 

2189 theta_range: The range of θ, `[θ_min, θ_max]` or `[θ_min, θ_max, θ_step]`, 

2190 in radians, sampled every 0.01 without a step; None for a full turn, 

2191 [0, 2π]. 

2192 **kwargs: [Curve keywords][manimgx.mobjects.plotting.CurveOptions]: 

2193 `use_smoothing`, and the style keywords. 

2194 

2195 Returns: 

2196 A new [ParametricFunction][manimgx.ParametricFunction], not added to the 

2197 axes. 

2198 

2199 Examples: 

2200 ```python 

2201 import numpy as np 

2202 

2203 import manimgx as m 

2204 

2205 

2206 class AxesPlotPolarGraphExample(m.Scene): 

2207 def construct(self) -> None: 

2208 plane = m.PolarPlane(radius_max=3, size=7.5) 

2209 rose = plane.plot_polar_graph( 

2210 lambda theta: 3 * np.sin(5 * theta), color=m.ORANGE 

2211 ) 

2212 self.add(plane) 

2213 self.play(m.Create(rose), run_time=3) 

2214 ``` 

2215 """ 

2216 theta_range = theta_range if theta_range is not None else [0, 2 * PI] 

2217 return ParametricFunction( 

2218 function=lambda th: self.pr2pt(r_func(th), th), 

2219 t_range=theta_range, 

2220 **kwargs, 

2221 ) 

2222 

2223 def input_to_graph_point(self, x: float, graph: ParametricFunction) -> Point3D: 

2224 """Find the point of a graph at an input: at x, for a graph of 

2225 [plot][manimgx.Axes.plot]; at a value of its parameter, for another curve. 

2226 

2227 `i2gp` is its short name. The input may be past the graph's ends: the point is 

2228 then its function's, beyond what is drawn. 

2229 

2230 Args: 

2231 x: The input: x, in the axes' coordinates, for a graph. 

2232 graph: The graph, or curve. 

2233 

2234 Returns: 

2235 The point, in scene coordinates. 

2236 

2237 Examples: 

2238 ```python 

2239 import numpy as np 

2240 

2241 import manimgx as m 

2242 

2243 

2244 class AxesInputToGraphPointExample(m.Scene): 

2245 def construct(self) -> None: 

2246 axes = m.Axes(x_range=[0, 7], y_range=[-1.5, 1.5, 0.5]) 

2247 curve = axes.plot(np.cos, color=m.BLUE) 

2248 dots = m.VGroup( 

2249 *(m.Dot(axes.i2gp(x, curve), radius=0.12) for x in range(7)) 

2250 ) 

2251 self.add(axes, curve, dots.set_color(m.YELLOW)) 

2252 ``` 

2253 """ 

2254 return graph.function(x) 

2255 

2256 def input_to_graph_coords( 

2257 self, x: float, graph: ParametricFunction 

2258 ) -> tuple[float, float]: 

2259 """Find the coordinates of a graph's point at an input: (x, f(x)), for a graph 

2260 of [plot][manimgx.Axes.plot]; for another curve, those of its point at a value 

2261 of its parameter. 

2262 

2263 Args: 

2264 x: The input: x, for a graph. 

2265 graph: The graph, or curve. 

2266 

2267 Returns: 

2268 The point's coordinates, (x, y). 

2269 """ 

2270 if ( 

2271 graph.underlying_function is None 

2272 ): # a curve, not a graph of y(x): its point's coordinates 

2273 coords = self.point_to_coords(graph.function(x)) 

2274 return float(coords[0]), float(coords[1]) 

2275 return (x, graph.underlying_function(x)) 

2276 

2277 i2gp = input_to_graph_point 

2278 """[input_to_graph_point][manimgx.Axes.input_to_graph_point], by a shorter name.""" 

2279 

2280 def get_graph_label( 

2281 self, 

2282 graph: ParametricFunction, 

2283 label: Label = "f(x)", 

2284 x_val: float | None = None, 

2285 direction: Vector3DLike = RIGHT, 

2286 buff: float = MED_SMALL_BUFF, 

2287 color: ParsableManimColor | None = None, 

2288 dot: bool = False, 

2289 dot_config: Style | None = None, 

2290 ) -> Mobject: 

2291 r"""Make a label for a graph, by one of its points: in the graph's color, unless 

2292 given another. 

2293 

2294 A string or a number is typeset with the axes' `label_constructor` (as math, 

2295 with [MathTex][manimgx.MathTex], by default); a mobject is used as it is, and 

2296 recolored too. The label is put next to the graph's point at `x_val`, toward 

2297 `direction`, then moved onto the screen if it is off it. Without `x_val`, the 

2298 point is the rightmost, of a hundred over the x-axis's range, that is below the 

2299 top of the frame. 

2300 

2301 Args: 

2302 label: The label: a string or a number, typeset as math, or a mobject. 

2303 x_val: The x of the point the label is put by; None for the rightmost on 

2304 screen. 

2305 direction: The direction the label is put toward, from the point. 

2306 buff: The gap between the point and the label, in scene units. 

2307 color: The label's color; None for the graph's. 

2308 dot: Whether a dot marks the point, as part of the label. 

2309 dot_config: [Style keywords][manimgx.drawing.paint.Style] for the dot; None 

2310 for none. 

2311 

2312 Returns: 

2313 The label, not added to the axes. 

2314 

2315 Examples: 

2316 ```python 

2317 import numpy as np 

2318 

2319 import manimgx as m 

2320 

2321 

2322 class AxesGetGraphLabelExample(m.Scene): 

2323 def construct(self) -> None: 

2324 axes = m.Axes(x_range=[-4, 4], y_range=[-2, 4], x_length=11) 

2325 parabola = axes.plot(lambda x: x**2 / 4, color=m.BLUE) 

2326 sine = axes.plot(np.sin, color=m.YELLOW) 

2327 parabola_label = axes.get_graph_label(parabola, "x^2 / 4") 

2328 sine_label = axes.get_graph_label( 

2329 sine, r"\sin x", x_val=m.PI / 2, direction=m.UP, dot=True 

2330 ) 

2331 self.add(axes, parabola, sine, parabola_label, sine_label) 

2332 ``` 

2333 """ 

2334 label_object: Mobject = self.x_axis._create_label_tex(label).set_color( 

2335 graph.get_color() if color is None else color 

2336 ) 

2337 if x_val is None: # the rightmost point of the graph that is on screen 

2338 xs = np.linspace(self.x_range[1], self.x_range[0], 100) 

2339 points = (self.input_to_graph_point(x, graph) for x in xs) 

2340 point = next( 

2341 (p for p in points if p[1] < config["frame_y_radius"]), 

2342 self.input_to_graph_point(xs[-1], graph), 

2343 ) 

2344 else: 

2345 point = self.input_to_graph_point(x_val, graph) 

2346 label_object.next_to(point, direction, buff=buff) 

2347 label_object.shift_onto_screen() 

2348 if dot: 

2349 label_object.add(Dot(point=point, **(dot_config or Style()))) 

2350 return label_object 

2351 

2352 def get_riemann_rectangles( 

2353 self, 

2354 graph: ParametricFunction, 

2355 x_range: Sequence[float] | None = None, 

2356 dx: float = 0.1, 

2357 input_sample_type: str = "left", 

2358 stroke_width: float = 1, 

2359 stroke_color: ParsableManimColor = BLACK, 

2360 fill_opacity: float = 1, 

2361 color: Iterable[ParsableManimColor] | ParsableManimColor = (BLUE, GREEN), 

2362 show_signed_area: bool = True, 

2363 bounded_graph: ParametricFunction | None = None, 

2364 blend: bool = False, 

2365 width_scale_factor: float = 1.001, 

2366 ) -> VGroup: 

2367 """Make Riemann rectangles for a graph: from the x-axis (or a second graph) up 

2368 to the graph, `dx` wide, their colors a gradient; outlined thinly in black 

2369 unless styled. 

2370 

2371 A rectangle begins at every `dx` from the start of `x_range`, the last before 

2372 its end. Each rises from the x-axis — or from `bounded_graph`, at its left 

2373 edge — to the graph at its left edge, its right edge or its center 

2374 (`input_sample_type`). With `show_signed_area`, a rectangle where the graph is 

2375 below its base takes the inverse of its color. 

2376 

2377 Args: 

2378 graph: The graph, of [plot][manimgx.Axes.plot]. 

2379 x_range: The range of x the rectangles cover, `[x_min, x_max]`; None for 

2380 the graph's (and `bounded_graph`'s, where both are). 

2381 dx: The rectangles' width, in the axes' units. 

2382 input_sample_type: Where each rectangle meets the graph: `"left"`, 

2383 `"right"` or `"center"`. 

2384 stroke_width: The width of the rectangles' outlines, in hundredths of a 

2385 scene unit. 

2386 stroke_color: The outlines' color (unless `blend`). 

2387 fill_opacity: The rectangles' opacity, from 0 to 1. 

2388 color: The rectangles' color, or colors for a gradient from the first 

2389 rectangle to the last. 

2390 show_signed_area: Whether a rectangle where the graph is below its base 

2391 takes the inverse of its color. 

2392 bounded_graph: A second graph, of [plot][manimgx.Axes.plot], the 

2393 rectangles rise from; None for the x-axis. 

2394 blend: Whether each outline takes its rectangle's color, rather than 

2395 `stroke_color`. 

2396 width_scale_factor: How much wider than `dx` each rectangle is made, so 

2397 that neighbours meet without a seam. 

2398 

2399 Returns: 

2400 A new group of the rectangles, from left to right; not added to the axes. 

2401 

2402 Examples: 

2403 ```python 

2404 import manimgx as m 

2405 

2406 

2407 class AxesGetRiemannRectanglesExample(m.Scene): 

2408 def construct(self) -> None: 

2409 axes = m.Axes(x_range=[-3, 3], y_range=[-2, 4], y_length=6.5) 

2410 graph = axes.plot(lambda x: x**2 / 2 - 1, color=m.YELLOW) 

2411 coarse, fine = ( 

2412 axes.get_riemann_rectangles(graph, x_range=[-2.5, 2.5], dx=dx) 

2413 for dx in (0.5, 0.1) 

2414 ) 

2415 self.add(axes, coarse, graph) 

2416 self.play(m.Transform(coarse, fine), run_time=2) 

2417 ``` 

2418 """ 

2419 if x_range is None: 

2420 if bounded_graph is None: 

2421 x_range = [graph.t_min, graph.t_max] 

2422 else: 

2423 x_min = max(graph.t_min, bounded_graph.t_min) 

2424 x_max = min(graph.t_max, bounded_graph.t_max) 

2425 x_range = [x_min, x_max] 

2426 rectangles = VGroup() 

2427 x_range_array = np.arange(x_range[0], x_range[1], dx) 

2428 colors = color_gradient(parse_colors(color), len(x_range_array)) 

2429 for x, color_x in zip(x_range_array, colors, strict=True): 

2430 if input_sample_type == "left": 

2431 sample_input = x 

2432 elif input_sample_type == "right": 

2433 sample_input = x + dx 

2434 elif input_sample_type == "center": 

2435 sample_input = x + 0.5 * dx 

2436 else: 

2437 raise ValueError("Invalid input sample type") 

2438 graph_point = self.input_to_graph_point(sample_input, graph) 

2439 if bounded_graph is None or bounded_graph.underlying_function is None: 

2440 y_point = _origin_shift(self.y_range) 

2441 else: 

2442 y_point = bounded_graph.underlying_function(x) 

2443 points = np.array( 

2444 [ 

2445 self.coords_to_point(x, y_point), 

2446 self.coords_to_point(x + width_scale_factor * dx, y_point), 

2447 graph_point, 

2448 ] 

2449 ) 

2450 low, high = points.min(axis=0), points.max(axis=0) 

2451 rect = Rectangle() 

2452 rect.stretch_to_fit_width(high[0] - low[0]) 

2453 rect.stretch_to_fit_height(high[1] - low[1]) 

2454 rect.shift((low + high) / 2 - rect.get_center()) 

2455 rectangles.add(rect) 

2456 if self.p2c(graph_point)[1] < y_point and show_signed_area: 

2457 color_x = invert_color(color_x) 

2458 if blend: 

2459 stroke_color = color_x 

2460 rect.set_style( 

2461 fill_color=color_x, 

2462 fill_opacity=fill_opacity, 

2463 stroke_color=stroke_color, 

2464 stroke_width=stroke_width, 

2465 ) 

2466 return rectangles 

2467 

2468 def get_area( 

2469 self, 

2470 graph: ParametricFunction, 

2471 x_range: Sequence[float] | None = None, 

2472 color: ParsableManimColor | Iterable[ParsableManimColor] = (BLUE, GREEN), 

2473 opacity: float = 0.3, 

2474 bounded_graph: ParametricFunction | None = None, 

2475 **kwargs: Unpack[StyleBase], 

2476 ) -> Polygon: 

2477 """Make the area between a graph and the x-axis, or between two graphs, over a 

2478 range of x: a polygon, blue to green and translucent unless styled. 

2479 

2480 The area's edge follows the graph's own points, and closes along the x-axis, or 

2481 back along `bounded_graph`; its fill and outline both take `color` and 

2482 `opacity`. Two graphs whose ranges do not meet raise a ValueError. 

2483 

2484 Args: 

2485 x_range: The range of x, `(x_min, x_max)`; None for the graph's. 

2486 color: The area's color, or colors for a gradient. 

2487 opacity: The area's opacity, from 0 to 1. 

2488 bounded_graph: A second graph the area reaches to, rather than the x-axis; 

2489 None for the x-axis. Only the range both graphs span is covered. 

2490 **kwargs: [Style keywords][manimgx.drawing.paint.Style] for the polygon, but 

2491 its colors and opacities: `stroke_width`, …. 

2492 

2493 Returns: 

2494 A new [Polygon][manimgx.Polygon], not added to the axes. 

2495 

2496 Examples: 

2497 ```python 

2498 import manimgx as m 

2499 

2500 

2501 class AxesGetAreaExample(m.Scene): 

2502 def construct(self) -> None: 

2503 axes = m.Axes(x_range=[0, 5], y_range=[0, 6], y_length=6.5) 

2504 curve = axes.plot(lambda x: 5 - (x - 2.5) ** 2 / 2, color=m.BLUE) 

2505 line = axes.plot(lambda x: x / 2, color=m.YELLOW) 

2506 under = axes.get_area(curve, x_range=(0.5, 2)) 

2507 between = axes.get_area( 

2508 curve, x_range=(3, 4.5), bounded_graph=line, color=m.RED 

2509 ) 

2510 self.add(axes, under, between, curve, line) 

2511 ``` 

2512 """ 

2513 if x_range is None: 

2514 a = graph.t_min 

2515 b = graph.t_max 

2516 else: 

2517 a, b = x_range 

2518 if bounded_graph is not None: 

2519 if bounded_graph.t_min > b: 

2520 raise ValueError(f"Ranges not matching: {bounded_graph.t_min} < {b}") 

2521 if bounded_graph.t_max < a: 

2522 raise ValueError(f"Ranges not matching: {bounded_graph.t_max} > {a}") 

2523 a = max(a, bounded_graph.t_min) 

2524 b = min(b, bounded_graph.t_max) 

2525 if bounded_graph is None: 

2526 points = [ 

2527 self.c2p(a), 

2528 graph.function(a), 

2529 *self._points_between(graph, a, b), 

2530 graph.function(b), 

2531 self.c2p(b), 

2532 ] 

2533 else: 

2534 graph_points, bounded_graph_points = ( 

2535 [g.function(a), *self._points_between(g, a, b), g.function(b)] 

2536 for g in (graph, bounded_graph) 

2537 ) 

2538 points = graph_points + bounded_graph_points[::-1] 

2539 return Polygon(*points, **kwargs).set_opacity(opacity).set_color(color) 

2540 

2541 def _points_between( 

2542 self, graph: ParametricFunction, a: float, b: float 

2543 ) -> Point3D_Array: 

2544 """The graph's points whose x on the axes is from `a` to `b`, in order: their 

2545 coordinates read all at once.""" 

2546 x = self.p2c(graph.points)[:, 0] 

2547 return graph.points[(a <= x) & (x <= b)] 

2548 

2549 def angle_of_tangent( 

2550 self, x: float, graph: ParametricFunction, dx: float = 1e-08 

2551 ) -> float: 

2552 """Find the angle of a graph's tangent at an input, in the axes' coordinates. 

2553 

2554 The tangent is taken from the graph's point at `x` to its point at `x + dx`. 

2555 

2556 Args: 

2557 x: The input: x, for a graph of [plot][manimgx.Axes.plot]. 

2558 dx: The step the tangent is taken over, in the axes' units. 

2559 

2560 Returns: 

2561 The angle, in radians, counterclockwise from the direction of the x-axis, 

2562 measured in the axes' coordinates: not as drawn, where their units differ. 

2563 """ 

2564 p0 = np.array([*self.input_to_graph_coords(x, graph)]) 

2565 p1 = np.array([*self.input_to_graph_coords(x + dx, graph)]) 

2566 return angle_of_vector(p1 - p0) 

2567 

2568 def slope_of_tangent( 

2569 self, x: float, graph: ParametricFunction, dx: float = 1e-08 

2570 ) -> float: 

2571 """Find the slope of a graph's tangent at an input: its derivative, dy/dx, in 

2572 the axes' coordinates. 

2573 

2574 It is the tangent of [angle_of_tangent][manimgx.Axes.angle_of_tangent]'s angle. 

2575 

2576 Args: 

2577 x: The input: x, for a graph of [plot][manimgx.Axes.plot]. 

2578 dx: The step the tangent is taken over, in the axes' units. 

2579 """ 

2580 return float(np.tan(self.angle_of_tangent(x, graph, dx))) 

2581 

2582 def plot_derivative_graph( 

2583 self, graph: ParametricFunction, **kwargs: Unpack[PlotOptions] 

2584 ) -> ParametricFunction: 

2585 """Plot the derivative of a graph: at each x, its 

2586 [slope][manimgx.Axes.slope_of_tangent]; green unless styled. 

2587 

2588 Args: 

2589 **kwargs: [Plot keywords][manimgx.mobjects.plotting.PlotOptions]: 

2590 `x_range`, `color`, …. 

2591 

2592 Returns: 

2593 A new [ParametricFunction][manimgx.ParametricFunction], not added to the 

2594 axes. 

2595 

2596 Examples: 

2597 ```python 

2598 import manimgx as m 

2599 

2600 

2601 class AxesPlotDerivativeGraphExample(m.Scene): 

2602 def construct(self) -> None: 

2603 axes = m.Axes(x_range=[-3, 3], y_range=[-3, 4], y_length=6.5) 

2604 cubic = axes.plot(lambda x: x**3 / 6 - x, color=m.BLUE) 

2605 derivative = axes.plot_derivative_graph(cubic) 

2606 labels = m.VGroup( 

2607 axes.get_graph_label(cubic, "f(x)", x_val=-1.4, direction=m.UP), 

2608 axes.get_graph_label(derivative, "f'(x)", x_val=2.5), 

2609 ) 

2610 self.add(axes, cubic, labels[0]) 

2611 self.play(m.Create(derivative), m.FadeIn(labels[1])) 

2612 ``` 

2613 """ 

2614 if kwargs.get("color") is None: # not given, None too 

2615 kwargs["color"] = GREEN 

2616 return self.plot(lambda x: self.slope_of_tangent(x, graph), **kwargs) 

2617 

2618 def plot_antiderivative_graph( 

2619 self, 

2620 graph: ParametricFunction, 

2621 y_intercept: float = 0, 

2622 samples: int = 50, 

2623 **kwargs: Unpack[PlotOptions], 

2624 ) -> ParametricFunction: 

2625 """Plot an antiderivative of a graph: at each x, the integral of the graph from 

2626 0 to x, plus `y_intercept`. 

2627 

2628 Each value is a trapezoidal sum of the graph's values at `samples` points from 

2629 0 to x. 

2630 

2631 Args: 

2632 y_intercept: The antiderivative's value at 0. 

2633 samples: How many of the graph's values each integral sums. 

2634 **kwargs: [Plot keywords][manimgx.mobjects.plotting.PlotOptions]: 

2635 `x_range`, `color`, …. 

2636 

2637 Returns: 

2638 A new [ParametricFunction][manimgx.ParametricFunction], not added to the 

2639 axes. 

2640 

2641 Examples: 

2642 ```python 

2643 import manimgx as m 

2644 

2645 

2646 class AxesPlotAntiderivativeGraphExample(m.Scene): 

2647 def construct(self) -> None: 

2648 axes = m.Axes(x_range=[-3, 3], y_range=[-3, 3], y_length=6.5) 

2649 graph = axes.plot(lambda x: (x**2 - 2) / 3, color=m.RED) 

2650 antiderivative = axes.plot_antiderivative_graph( 

2651 graph, y_intercept=1, color=m.BLUE 

2652 ) 

2653 self.add(axes, graph) 

2654 self.play(m.Create(antiderivative)) 

2655 ``` 

2656 """ 

2657 axis = 1 if kwargs.get("use_vectorized", False) else 0 

2658 f_vec = np.vectorize( 

2659 graph.underlying_function 

2660 or (lambda x: self.input_to_graph_coords(x, graph)[1]) 

2661 ) 

2662 

2663 def antideriv(x: float) -> float: 

2664 x_vals = np.linspace(0, x, samples, axis=axis) 

2665 return float(np.trapezoid(f_vec(x_vals), x_vals) + y_intercept) 

2666 

2667 return self.plot(antideriv, **kwargs) 

2668 

2669 def get_secant_slope_group( 

2670 self, 

2671 x: float, 

2672 graph: ParametricFunction, 

2673 dx: float | None = None, 

2674 dx_line_color: ParsableManimColor = PURE_YELLOW, 

2675 dy_line_color: ParsableManimColor | None = None, 

2676 dx_label: Label | None = None, 

2677 dy_label: Label | None = None, 

2678 include_secant_line: bool = True, 

2679 secant_line_color: ParsableManimColor = GREEN, 

2680 secant_line_length: float = 10, 

2681 ) -> SecantSlopeGroup: 

2682 """Make a secant's construction on a graph, between its points at `x` and 

2683 `x + dx`: the legs dx and df, their labels, and the secant through both points. 

2684 

2685 The dx leg runs across from the first point, and the df leg up (or down) to the 

2686 second, in the graph's color unless given another. The labels, typeset as math 

2687 unless mobjects, are scaled down together to fit their legs (to 80% of the dx 

2688 leg's width and of the df leg's height), and put below the dx leg and right of 

2689 the df leg (above and left, for a negative `dx`), each in its leg's color. The 

2690 secant is `secant_line_length` long, centered between the points. 

2691 

2692 Args: 

2693 x: The input of the first point: its x. 

2694 dx: The step to the second point, in the axes' units; None for a tenth of 

2695 the x-axis's range. 

2696 dx_line_color: The dx leg's color. 

2697 dy_line_color: The df leg's color; None for the graph's. 

2698 dx_label: The dx leg's label: a string, a number or a mobject; None for 

2699 none. 

2700 dy_label: The df leg's label, likewise; None for none. 

2701 include_secant_line: Whether the construction includes the secant. 

2702 secant_line_color: The secant's color. 

2703 secant_line_length: The secant's length, in scene units. 

2704 

2705 Returns: 

2706 A new [SecantSlopeGroup][manimgx.mobjects.plotting.SecantSlopeGroup], 

2707 not added to the axes: its parts are its `dx_line`, `df_line`, `dx_label`, 

2708 `df_label` and `secant_line`. 

2709 

2710 Examples: 

2711 ```python 

2712 import manimgx as m 

2713 

2714 

2715 class AxesGetSecantSlopeGroupExample(m.Scene): 

2716 def construct(self) -> None: 

2717 axes = m.Axes(x_range=[0, 5], y_range=[0, 7], y_length=6.5) 

2718 graph = axes.plot(lambda x: x**2 / 4, color=m.BLUE) 

2719 secant = axes.get_secant_slope_group( 

2720 2, 

2721 graph, 

2722 dx=2, 

2723 dx_label="dx", 

2724 dy_label="dy", 

2725 secant_line_length=7, 

2726 secant_line_color=m.RED, 

2727 ) 

2728 self.add(axes, graph) 

2729 self.play(m.Create(secant)) 

2730 ``` 

2731 """ 

2732 group = SecantSlopeGroup() 

2733 dx = dx or float(self.x_range[1] - self.x_range[0]) / 10 

2734 dy_line_color = dy_line_color or graph.get_color() 

2735 p1 = self.input_to_graph_point(x, graph) 

2736 p2 = self.input_to_graph_point(x + dx, graph) 

2737 interim_point = p2[0] * RIGHT + p1[1] * UP 

2738 group.dx_line = Line(p1, interim_point, color=dx_line_color) 

2739 group.df_line = Line(interim_point, p2, color=dy_line_color) 

2740 group.add(group.dx_line, group.df_line) 

2741 labels = VGroup() 

2742 if dx_label is not None: 

2743 group.dx_label = self.x_axis._create_label_tex(dx_label) 

2744 labels.add(group.dx_label) 

2745 group.add(group.dx_label) 

2746 if dy_label is not None: 

2747 group.df_label = self.x_axis._create_label_tex(dy_label) 

2748 labels.add(group.df_label) 

2749 group.add(group.df_label) 

2750 if len(labels) > 0: 

2751 max_width = 0.8 * group.dx_line.width 

2752 max_height = 0.8 * group.df_line.height 

2753 if labels.width > max_width: 

2754 labels.width = max_width 

2755 if labels.height > max_height: 

2756 labels.height = max_height 

2757 if dx_label is not None: 

2758 group.dx_label.next_to( 

2759 group.dx_line, np.sign(dx) * DOWN, buff=group.dx_label.height / 2 

2760 ) 

2761 group.dx_label.set_color(group.dx_line.get_color()) 

2762 if dy_label is not None: 

2763 group.df_label.next_to( 

2764 group.df_line, np.sign(dx) * RIGHT, buff=group.df_label.height / 2 

2765 ) 

2766 group.df_label.set_color(group.df_line.get_color()) 

2767 if include_secant_line: 

2768 group.secant_line = Line(p1, p2, color=secant_line_color) 

2769 group.secant_line.scale(secant_line_length / group.secant_line.get_length()) 

2770 group.add(group.secant_line) 

2771 return group 

2772 

2773 def get_vertical_lines_to_graph( 

2774 self, 

2775 graph: ParametricFunction, 

2776 x_range: Sequence[float] | None = None, 

2777 num_lines: int = 20, 

2778 **kwargs: Unpack[AxisLine], 

2779 ) -> VGroup: 

2780 """Make lines from the x-axis to a graph, evenly spaced over a range of x: 

2781 dashed, white and thin unless styled. 

2782 

2783 Args: 

2784 x_range: The range of x, `[x_min, x_max]`: the first line at x_min, the 

2785 last at x_max; None for the x-axis's range. 

2786 num_lines: How many lines. 

2787 **kwargs: [Axis line keywords][manimgx.mobjects.plotting.AxisLine]: 

2788 the lines' class, keywords, `color` and `stroke_width`. 

2789 

2790 Returns: 

2791 A new group of the lines, from left to right; not added to the axes. 

2792 

2793 Examples: 

2794 ```python 

2795 import numpy as np 

2796 

2797 import manimgx as m 

2798 

2799 

2800 class AxesGetVerticalLinesToGraphExample(m.Scene): 

2801 def construct(self) -> None: 

2802 axes = m.Axes(x_range=[0, 8], y_range=[-1, 1, 0.5], y_length=5) 

2803 curve = axes.plot( 

2804 lambda x: np.sin(2 * x) * np.exp(-x / 4), color=m.YELLOW 

2805 ) 

2806 lines = axes.get_vertical_lines_to_graph( 

2807 curve, x_range=[0.5, 7.5], num_lines=15, color=m.BLUE 

2808 ) 

2809 self.add(axes, curve) 

2810 self.play(m.Create(lines)) 

2811 ``` 

2812 """ 

2813 x_range = x_range if x_range is not None else self.x_range 

2814 return VGroup( 

2815 *( 

2816 self.get_vertical_line(self.i2gp(x, graph), **kwargs) 

2817 for x in np.linspace(x_range[0], x_range[1], num_lines) 

2818 ) 

2819 ) 

2820 

2821 def get_T_label( 

2822 self, 

2823 x_val: float, 

2824 graph: ParametricFunction, 

2825 label: float | str | Mobject | None = None, 

2826 label_color: ParsableManimColor | None = None, 

2827 triangle_size: float = MED_SMALL_BUFF, 

2828 triangle_color: ParsableManimColor | None = WHITE, 

2829 line_func: type[Line] = Line, 

2830 line_color: ParsableManimColor = PURE_YELLOW, 

2831 ) -> VGroup: 

2832 """Make a T-label for a value of x: a small triangle under the x-axis pointing 

2833 up at the value, a label below the triangle, and a line from the x-axis up to 

2834 the graph. 

2835 

2836 Args: 

2837 x_val: The value of x it marks. 

2838 graph: The graph the line reaches. 

2839 label: The label below the triangle: a string or a number, typeset as math, 

2840 or a mobject; None for none. 

2841 label_color: The label's color; None to leave it as it is. 

2842 triangle_size: The triangle's height, in scene units. 

2843 triangle_color: The triangle's color. 

2844 line_func: The class of the line: [Line][manimgx.Line] (solid), 

2845 [DashedLine][manimgx.DashedLine], …. 

2846 line_color: The line's color. 

2847 

2848 Returns: 

2849 A new group of the label (if any), the triangle and the line; not added to 

2850 the axes. 

2851 

2852 Examples: 

2853 ```python 

2854 import numpy as np 

2855 

2856 import manimgx as m 

2857 

2858 

2859 class AxesGetTLabelExample(m.Scene): 

2860 def construct(self) -> None: 

2861 axes = m.Axes(x_range=[0, 10], y_range=[0, 10], y_length=6) 

2862 graph = axes.plot(lambda x: 3 * np.sqrt(x), color=m.BLUE) 

2863 t_label = axes.get_T_label(4, graph, label=m.MathTex("x = 4")) 

2864 self.add(axes, graph) 

2865 self.play(m.FadeIn(t_label)) 

2866 ``` 

2867 """ 

2868 T_label_group = VGroup() 

2869 triangle = RegularPolygon(n=3, start_angle=np.pi / 2, stroke_width=0).set_fill( 

2870 color=triangle_color, opacity=1 

2871 ) 

2872 triangle.height = triangle_size 

2873 triangle.move_to(self.coords_to_point(x_val, 0), UP) 

2874 if label is not None: 

2875 t_label = self.x_axis._create_label_tex(label) 

2876 if label_color is not None: 

2877 t_label.set_color(label_color) 

2878 t_label.next_to(triangle, DOWN) 

2879 T_label_group.add(t_label) 

2880 v_line = self.get_vertical_line( 

2881 self.i2gp(x_val, graph), color=line_color, line_func=line_func 

2882 ) 

2883 T_label_group.add(triangle, v_line) 

2884 return T_label_group 

2885 

2886 def plot_line_graph( 

2887 self, 

2888 x_values: Iterable[float], 

2889 y_values: Iterable[float], 

2890 z_values: Iterable[float] | None = None, 

2891 line_color: ParsableManimColor = PURE_YELLOW, 

2892 add_vertex_dots: bool = True, 

2893 vertex_dot_radius: float = DEFAULT_DOT_RADIUS, 

2894 vertex_dot_style: Style | None = None, 

2895 **kwargs: Unpack[Style], 

2896 ) -> VDict: 

2897 """Plot a line graph: straight segments through points given by their 

2898 coordinates, with a dot at each point; bright yellow (`PURE_YELLOW`), with white 

2899 dots, unless styled. Empty inputs produce an empty graph. 

2900 

2901 Args: 

2902 x_values: The points' x coordinates. 

2903 y_values: Their y coordinates, as many. 

2904 z_values: Their z coordinates, on three-dimensional axes; None for 0. 

2905 line_color: The line's color, unless the keywords give a `color`. 

2906 add_vertex_dots: Whether a dot marks each point. 

2907 vertex_dot_radius: The dots' radius, in scene units. 

2908 vertex_dot_style: [Style keywords][manimgx.drawing.paint.Style] for the dots; 

2909 None for none. 

2910 **kwargs: [Style keywords][manimgx.drawing.paint.Style] for the line. 

2911 

2912 Returns: 

2913 A new [VDict][manimgx.VDict], not added to the axes, with the line 

2914 under `"line_graph"` and the dots, in a group, under `"vertex_dots"`. 

2915 

2916 Examples: 

2917 ```python 

2918 import manimgx as m 

2919 

2920 

2921 class AxesPlotLineGraphExample(m.Scene): 

2922 def construct(self) -> None: 

2923 axes = m.Axes(x_range=[0, 7], y_range=[0, 5], y_length=6) 

2924 graph = axes.plot_line_graph( 

2925 x_values=[0, 1.5, 2, 2.8, 4, 6.25], 

2926 y_values=[1, 3, 2.25, 4, 2.5, 1.75], 

2927 line_color=m.ORANGE, 

2928 vertex_dot_radius=0.12, 

2929 vertex_dot_style={"color": m.PURPLE}, 

2930 stroke_width=6, 

2931 ) 

2932 self.add(axes.add_coordinates()) 

2933 self.play(m.Create(graph)) 

2934 ``` 

2935 """ 

2936 xs, ys = ( 

2937 np.array(list(x_values), dtype=float), 

2938 np.array(list(y_values), dtype=float), 

2939 ) 

2940 zs = ( 

2941 np.zeros(xs.shape) 

2942 if z_values is None 

2943 else np.array(list(z_values), dtype=float) 

2944 ) 

2945 line_graph = VDict() 

2946 if kwargs.get("color") is None: # not given, None too 

2947 kwargs["color"] = line_color 

2948 graph = VMobject(**kwargs) 

2949 vertices = self.coords_to_point(*np.array((xs, ys, zs))).T 

2950 graph.set_points_as_corners(vertices) 

2951 line_graph["line_graph"] = graph 

2952 if add_vertex_dots: 

2953 line_graph["vertex_dots"] = VGroup( 

2954 *( 

2955 Dot( 

2956 point=vertex.copy(), # the dot retains its center 

2957 radius=vertex_dot_radius, 

2958 **(vertex_dot_style or Style()), 

2959 ) 

2960 for vertex in vertices 

2961 ) 

2962 ) 

2963 return line_graph 

2964 

2965 def __matmul__(self, coord: Point3DLike | Mobject) -> np.ndarray: 

2966 if isinstance(coord, Mobject): 

2967 coord = coord.get_center() 

2968 return self.coords_to_point(*coord) 

2969 

2970 

2971def _full_range(given: Sequence[float] | None, radius: float) -> Sequence[float]: 

2972 """An axis' (min, max, step): the frame's width or height, by 1, unless given.""" 

2973 if given is None: 

2974 return [round(-radius), round(radius), 1] 

2975 return [*given, 1] if len(given) == 2 else given 

2976 

2977 

2978def _origin_shift(axis_range: Sequence[float]) -> float: 

2979 """Where an axis crosses the others: 0, or the end of its range nearest 0.""" 

2980 if axis_range[0] > 0: 

2981 return axis_range[0] 

2982 if axis_range[1] < 0: 

2983 return axis_range[1] 

2984 return 0 

2985 

2986 

2987class _AxesOptions(_Style, total=False): 

2988 """AxesOptions's keys, open, for the keywords that add to them.""" 

2989 

2990 axis_config: NumberLineOptions | None 

2991 """[Number line keywords][manimgx.NumberLine] 

2992 for every axis: `include_numbers`, `font_size`, `color`, … (default None: none).""" 

2993 x_axis_config: NumberLineOptions | None 

2994 """Number line keywords for the x-axis, over `axis_config`'s (default None: 

2995 none).""" 

2996 y_axis_config: NumberLineOptions | None 

2997 """Number line keywords for the y-axis, over `axis_config`'s (default None: 

2998 none).""" 

2999 tips: bool 

3000 """Whether each axis ends in an arrow tip (default True; a plane's axes have none, 

3001 unless `axis_config` includes `include_tip`).""" 

3002 

3003 

3004class AxesOptions(_AxesOptions, total=False, closed=True): 

3005 """[Axes][manimgx.Axes]' keywords but their ranges and lengths, for the classes that 

3006 pass them on ([ThreeDAxes][manimgx.ThreeDAxes], the planes, 

3007 [BarChart][manimgx.BarChart]): their axes' configs and tips, with the style 

3008 keywords.""" 

3009 

3010 

3011def _origin_tick(config_: NumberLineOptions) -> NumberLineOptions: 

3012 """A linear axis leaves its origin unticked (the other axis crosses there).""" 

3013 return config_ | { 

3014 "exclude_origin_tick": isinstance( 

3015 config_.get("scaling", LinearBase()), LinearBase 

3016 ) 

3017 } 

3018 

3019 

3020class ThreeDAxes(Axes): 

3021 """Three-dimensional axes: a z-axis out of the screen, through the origin of x- and 

3022 y-axes; white, with tips, and shaded by a three-dimensional scene's light, unless 

3023 configured. 

3024 

3025 The z-axis is made as the others, over `z_range`, and points OUT, crossing them at 

3026 its 0 (or at the end of its range nearest 0). Each axis is drawn as short pieces, 

3027 shaded as three-dimensional objects are, with a slight sheen toward the light. 

3028 Coordinates are converted with three numbers, `axes.c2p(x, y, z)`, and everything 

3029 [Axes][manimgx.Axes] do, these axes do. Seen 

3030 from straight above, they look like two-dimensional axes: turn the camera 

3031 ([set_camera_orientation][manimgx.ThreeDScene.set_camera_orientation]) to see 

3032 their depth. 

3033 

3034 Common axis options are captured when construction starts; each 

3035 finished number line retains its own runtime defaults. 

3036 

3037 Args: 

3038 x_range: The x-axis's range, `[x_min, x_max, x_step]`, or `[x_min, x_max]` for 

3039 a step of 1; None for [-7, 7, 1]. 

3040 y_range: The y-axis's range, likewise; None for [-4, 4, 1]. 

3041 z_range: The z-axis's range, likewise; None for [-7, 7, 1]. 

3042 x_length: The x-axis's length, in scene units; None for the frame's short side 

3043 plus 2.5 (10.5, in a wide video and a tall one), or `unit_size` per unit if 

3044 the axis's config gives one. 

3045 y_length: The y-axis's length, in scene units; None for 10.5 too, or `unit_size` 

3046 per unit if the axis's config gives one. 

3047 z_length: The z-axis's length, in scene units; None for the frame's short side 

3048 less 1.5 (6.5), or `unit_size` per unit if the axis's config gives one. 

3049 z_axis_config: [Number line keywords][manimgx.NumberLine] 

3050 for the z-axis, over `axis_config`'s; None for none. 

3051 **kwargs: [Axes keywords][manimgx.mobjects.plotting.AxesOptions]: 

3052 `axis_config`, `x_axis_config`, `y_axis_config`, `tips`. 

3053 

3054 Examples: 

3055 ```python 

3056 import manimgx as m 

3057 

3058 

3059 class ThreeDAxesExample(m.ThreeDScene): 

3060 def construct(self) -> None: 

3061 self.set_camera_orientation(phi=60 * m.DEGREES, theta=-50 * m.DEGREES) 

3062 axes = m.ThreeDAxes( 

3063 x_range=(-4, 4), 

3064 y_range=(-4, 4), 

3065 z_range=(-3, 3), 

3066 x_length=8, 

3067 y_length=8, 

3068 z_length=6, 

3069 ) 

3070 dot = m.Dot3D(axes.c2p(2, 3, 2), radius=0.15, color=m.YELLOW) 

3071 self.add(axes, axes.get_axis_labels(), dot) 

3072 ``` 

3073 """ 

3074 

3075 def __init__( 

3076 self, 

3077 x_range: Sequence[float] | None = (-6, 6, 1), 

3078 y_range: Sequence[float] | None = (-5, 5, 1), 

3079 z_range: Sequence[float] | None = (-4, 4, 1), 

3080 x_length: float | None = None, 

3081 y_length: float | None = None, 

3082 z_length: float | None = None, 

3083 z_axis_config: NumberLineOptions | None = None, 

3084 **kwargs: Unpack[AxesOptions], 

3085 ): 

3086 axis_config = merged_axis_config( 

3087 {"include_tip": kwargs.get("tips", True), "numbers_to_exclude": [0]}, 

3088 kwargs.get("axis_config"), 

3089 ) 

3090 kwargs["axis_config"] = axis_config 

3091 super().__init__( 

3092 x_range=x_range, 

3093 x_length=x_length, 

3094 y_range=y_range, 

3095 y_length=y_length, 

3096 **kwargs, 

3097 ) 

3098 self.z_range = z_range 

3099 """The z-axis's range, as given.""" 

3100 z_axis_config = _origin_tick(merged_axis_config(axis_config, z_axis_config)) 

3101 self.dimension = 3 

3102 z_axis = self._create_axis(self.z_range, z_axis_config, z_length, 2) 

3103 z_origin = _origin_shift([z_axis.x_min, z_axis.x_max]) 

3104 z_axis.rotate_about_number(z_origin, -PI / 2, UP) 

3105 z_axis.rotate_about_number(z_origin, angle_of_vector(DOWN)) 

3106 z_axis.shift(-z_axis.number_to_point(z_origin)) 

3107 z_axis.shift( 

3108 self.x_axis.number_to_point( 

3109 _origin_shift([self.x_axis.x_min, self.x_axis.x_max]) 

3110 ) 

3111 ) 

3112 self.axes.add(z_axis) 

3113 self.add(z_axis) 

3114 self.z_axis = z_axis 

3115 """The z-axis, a [NumberLine][manimgx.NumberLine].""" 

3116 self.z_length = z_axis.get_length() 

3117 self._add_3d_pieces() 

3118 self._set_axis_shading() 

3119 

3120 def _fitting_length(self, index: int) -> float: 

3121 """The length of an axis given none (0: x, 1: y, 2: z), from the frame's short 

3122 side, which a wide video and a tall one share.""" 

3123 short = min(config.frame_width, config.frame_height) 

3124 return short - 1.5 if index == 2 else short + 2.5 

3125 

3126 def _add_3d_pieces(self) -> None: 

3127 for axis in self.axes: 

3128 drawing = VMobject(z_index=axis.z_index) 

3129 drawing._geometry, drawing.paint = axis._geometry, axis.paint 

3130 axis.add(drawing.get_pieces(20)) 

3131 axis.set_stroke(width=0, family=False) 

3132 axis.set_shade_in_3d(True) 

3133 

3134 def _set_axis_shading(self) -> None: 

3135 """A sheen toward the light, across each whole axis (not piece by piece).""" 

3136 toward_light = np.sign(9 * DOWN + 7 * LEFT + 10 * OUT) 

3137 for axis in self.axes: 

3138 for piece in axis.family_members_with_points(): 

3139 if isinstance(piece, VMobject): 

3140 piece.gradient_frame = axis 

3141 piece.set_sheen(0.2, toward_light) 

3142 

3143 def get_y_axis_label( 

3144 self, 

3145 label: Label, 

3146 edge: Vector3DLike = UR, 

3147 direction: Vector3DLike = UR, 

3148 buff: float = SMALL_BUFF, 

3149 rotation: float = PI / 2, 

3150 rotation_axis: Vector3DLike = OUT, 

3151 ) -> Mobject: 

3152 """Make a label for the y-axis, by its end, turned to lie along it. 

3153 

3154 A string or a number is typeset with the axes' `label_constructor` (as math, 

3155 with [MathTex][manimgx.MathTex], by default); a mobject is used as it is. The 

3156 label is put next to a corner of the axis, toward `direction`, moved onto the 

3157 screen if it is off it, then turned about its center. 

3158 

3159 Args: 

3160 label: The label: a string, a number or a mobject. 

3161 edge: The corner of the axis the label is put by, as a direction: UR, the 

3162 upper right one, by its end. 

3163 direction: The direction the label is put toward, from that corner. 

3164 buff: The gap between the corner and the label, in scene units. 

3165 rotation: The angle the label is turned through, in radians: a quarter 

3166 turn, counterclockwise. 

3167 rotation_axis: The axis it is turned about: OUT turns it in the xy-plane. 

3168 

3169 Returns: 

3170 The label, not added to the axes. 

3171 """ 

3172 placed = super().get_y_axis_label(label, edge, direction, buff) 

3173 return placed.rotate(rotation, axis=rotation_axis) 

3174 

3175 def get_z_axis_label( 

3176 self, 

3177 label: Label, 

3178 edge: Vector3DLike = OUT, 

3179 direction: Vector3DLike = RIGHT, 

3180 buff: float = SMALL_BUFF, 

3181 rotation: float = PI / 2, 

3182 rotation_axis: Vector3DLike = RIGHT, 

3183 ) -> Mobject: 

3184 """Make a label for the z-axis, by its end, stood upright. 

3185 

3186 A string or a number is typeset with the axes' `label_constructor` (as math, 

3187 with [MathTex][manimgx.MathTex], by default); a mobject is used as it is. The 

3188 label is put next to the axis's end, toward `direction`, moved onto the screen 

3189 if it is off it, then turned about its center: by default a quarter turn about 

3190 RIGHT, which stands it up out of the xy-plane. 

3191 

3192 Args: 

3193 label: The label: a string, a number or a mobject. 

3194 edge: The point of the axis the label is put by, as a direction: OUT, its 

3195 end. 

3196 direction: The direction the label is put toward, from that point. 

3197 buff: The gap between the point and the label, in scene units. 

3198 rotation: The angle the label is turned through, in radians. 

3199 rotation_axis: The axis it is turned about. 

3200 

3201 Returns: 

3202 The label, not added to the axes. 

3203 """ 

3204 placed = self._get_axis_label(label, self.z_axis, edge, direction, buff) 

3205 return placed.rotate(rotation, axis=rotation_axis) 

3206 

3207 def get_axis_labels( 

3208 self, x_label: Label = "x", y_label: Label = "y", z_label: Label = "z" 

3209 ) -> VGroup: 

3210 """Make a label for each axis, by its end, as 

3211 [get_x_axis_label][manimgx.Axes.get_x_axis_label], 

3212 [get_y_axis_label][manimgx.ThreeDAxes.get_y_axis_label] and 

3213 [get_z_axis_label][manimgx.ThreeDAxes.get_z_axis_label] place them. 

3214 

3215 Args: 

3216 x_label: The x-axis's label: a string or a number, typeset as math, or a 

3217 mobject. 

3218 y_label: The y-axis's label, likewise. 

3219 z_label: The z-axis's label, likewise. 

3220 

3221 Returns: 

3222 A new group of the labels, kept as the axes' `axis_labels`; not added to 

3223 the axes. 

3224 """ 

3225 self.axis_labels = VGroup( 

3226 self.get_x_axis_label(x_label), 

3227 self.get_y_axis_label(y_label), 

3228 self.get_z_axis_label(z_label), 

3229 ) 

3230 return self.axis_labels 

3231 

3232 

3233class _Plane(Axes): 

3234 """Grid planes build styled backgrounds once and prepare their paths for transforms.""" 

3235 

3236 def __init__( 

3237 self, 

3238 *, 

3239 background_line_style: Style | None = None, 

3240 faded_line_style: Style | None = None, 

3241 faded_line_ratio: int = 1, 

3242 x_range: Sequence[float] | None = None, 

3243 y_range: Sequence[float] | None = None, 

3244 x_length: float | None = None, 

3245 y_length: float | None = None, 

3246 **kwargs: Unpack[AxesOptions], 

3247 ) -> None: 

3248 background_line_style = Style( 

3249 stroke_color=BLUE_D, stroke_width=2, stroke_opacity=1 

3250 ) | (background_line_style or Style()) 

3251 # a plane's unit is a scene unit, unless a length or a unit_size is given 

3252 kwargs["axis_config"] = merged_axis_config( 

3253 {"unit_size": 1}, kwargs.get("axis_config") 

3254 ) 

3255 super().__init__( 

3256 x_range=x_range, 

3257 y_range=y_range, 

3258 x_length=x_length, 

3259 y_length=y_length, 

3260 **kwargs, 

3261 ) 

3262 if faded_line_style is None: # the background lines at half strength 

3263 faded = background_line_style.copy() 

3264 if (width := faded.get("stroke_width")) is not None: 

3265 faded["stroke_width"] = width * 0.5 

3266 if (opacity := faded.get("stroke_opacity")) is not None: 

3267 faded["stroke_opacity"] = _halved(opacity) 

3268 if (opacity := faded.get("fill_opacity")) is not None: 

3269 faded["fill_opacity"] = _halved(opacity) 

3270 faded_line_style = faded 

3271 self.background_lines, self.faded_lines = self._get_lines(faded_line_ratio) 

3272 for lines, style in ( 

3273 (self.background_lines, background_line_style), 

3274 (self.faded_lines, faded_line_style), 

3275 ): 

3276 lines.set_style( 

3277 fill_color=style.get("fill_color"), 

3278 fill_opacity=style.get("fill_opacity"), 

3279 stroke_color=style.get("stroke_color"), 

3280 stroke_width=style.get("stroke_width"), 

3281 stroke_opacity=style.get("stroke_opacity"), 

3282 ) 

3283 self.add_to_back(self.faded_lines, self.background_lines) 

3284 

3285 def _get_lines(self, faded_line_ratio: int) -> tuple[VGroup, VGroup]: 

3286 raise NotImplementedError 

3287 

3288 def prepare_for_nonlinear_transform(self, num_inserted_curves: int = 50) -> Self: 

3289 """Split the plane's lines into many curves, so that a nonlinear function bends 

3290 them smoothly. 

3291 

3292 A function applied to the plane (with 

3293 [apply_function][manimgx.Mobject.apply_function] or 

3294 [apply_complex_function][manimgx.Mobject.apply_complex_function]) moves the 

3295 points of its lines, and a straight line is a single curve: moving its few 

3296 points would barely bend it. Each part of the plane with fewer curves than 

3297 `num_inserted_curves` is divided into that many. 

3298 

3299 Args: 

3300 num_inserted_curves: How many curves each line has at least. 

3301 

3302 Examples: 

3303 ```python 

3304 import numpy as np 

3305 

3306 import manimgx as m 

3307 

3308 

3309 class PlanePrepareForNonlinearTransformExample(m.Scene): 

3310 def construct(self) -> None: 

3311 plane = m.ComplexPlane(x_range=[-3, 3, 0.5], y_range=[-2, 2, 0.5]) 

3312 plane.prepare_for_nonlinear_transform() 

3313 self.add(plane) 

3314 self.play(plane.animate.apply_complex_function(np.sin), run_time=3) 

3315 ``` 

3316 """ 

3317 for mob in self.family_members_with_points(): 

3318 if isinstance(mob, VMobject): 

3319 num_curves = mob.get_num_curves() 

3320 if num_inserted_curves > num_curves: 

3321 mob.insert_n_curves(num_inserted_curves - num_curves) 

3322 return self 

3323 

3324 

3325class NumberPlaneOptions(_AxesOptions, total=False, closed=True): 

3326 """A [NumberPlane][manimgx.NumberPlane]'s keywords, for the scenes that pass them on 

3327 ([LinearTransformationScene][manimgx.LinearTransformationScene], …): its ranges, 

3328 sizes and grid, with the axes' keywords.""" 

3329 

3330 x_range: Sequence[float] | None 

3331 """The x-axis's range, `[x_min, x_max, x_step]`: a vertical line of the grid at 

3332 every step (default: the frame's width, by 1).""" 

3333 y_range: Sequence[float] | None 

3334 """The y-axis's range, `[y_min, y_max, y_step]`: a horizontal line of the grid at 

3335 every step (default: the frame's height, by 1).""" 

3336 x_length: float | None 

3337 """The x-axis's length, in scene units (default None: one scene unit per unit).""" 

3338 y_length: float | None 

3339 """The y-axis's length, in scene units (default None: one scene unit per unit).""" 

3340 background_line_style: Style | None 

3341 """[Style keywords][manimgx.drawing.paint.Style] for the grid's lines, over their 

3342 defaults: blue (`BLUE_D`), 2 wide, opaque (default None: none).""" 

3343 faded_line_style: Style | None 

3344 """[Style keywords][manimgx.drawing.paint.Style] for the fainter lines between them 

3345 (default None: the grid lines' style, at half their width and opacity).""" 

3346 faded_line_ratio: int 

3347 """How many parts the fainter lines divide each step of the grid into: 1 for no 

3348 fainter lines, 2 for one between each two grid lines (default 1).""" 

3349 

3350 

3351class NumberPlane(_Plane): 

3352 """A number plane: axes over a grid, a line at every step of each axis's range; 

3353 filling the frame, with the scene's own coordinates, unless sized. 

3354 

3355 The grid's lines are blue (`BLUE_D`) and 2 wide; with a `faded_line_ratio` above 

3356 1, fainter lines divide each step further, half as wide and half as opaque unless 

3357 styled. The lines are drawn behind the axes, which are white, 2 wide, without 

3358 ticks or tips; their numbers, when written, are small (font size 24), below and to 

3359 the right of their points. By default the ranges span the frame, one scene unit 

3360 per unit, so the plane's coordinates are the scene's. Everything 

3361 [Axes][manimgx.Axes] do, the plane does: converting coordinates, plotting, 

3362 labeling. 

3363 

3364 Background styles and the faded-line ratio are construction inputs; the plane 

3365 retains its drawn grid rather than those setup attributes. 

3366 

3367 Args: 

3368 x_range: The x-axis's range, `[x_min, x_max, x_step]`: a vertical line of the 

3369 grid at every step. None for the frame's width when the plane is made, by 

3370 1. 

3371 y_range: The y-axis's range, `[y_min, y_max, y_step]`: a horizontal line of 

3372 the grid at every step. None for the frame's height when the plane is made, 

3373 by 1. 

3374 x_length: The x-axis's length, in scene units; None for one scene unit per 

3375 unit. 

3376 y_length: The y-axis's length, in scene units; None for one scene unit per 

3377 unit. 

3378 background_line_style: [Style keywords][manimgx.drawing.paint.Style] for the 

3379 grid's lines, over their defaults; None for none. 

3380 faded_line_style: [Style keywords][manimgx.drawing.paint.Style] for the fainter 

3381 lines; None for the grid lines' style, at half their width and opacity. 

3382 faded_line_ratio: How many parts the fainter lines divide each step of the 

3383 grid into: 1 for no fainter lines, 2 for one between each two grid lines. 

3384 **kwargs: [Axes keywords][manimgx.mobjects.plotting.AxesOptions]: 

3385 `axis_config` over the plane's own (no ticks, no tips, font size 24), …; 

3386 `tips` is overridden by it, so tips need `include_tip` in `axis_config`. 

3387 

3388 Examples: 

3389 ```python 

3390 import manimgx as m 

3391 

3392 

3393 class NumberPlaneExample(m.Scene): 

3394 def construct(self) -> None: 

3395 plane = m.NumberPlane( 

3396 x_range=[-6.5, 6.5, 1], 

3397 y_range=[-4, 4, 1], 

3398 faded_line_ratio=2, 

3399 background_line_style={"stroke_color": m.TEAL}, 

3400 ) 

3401 arrow = m.Arrow(plane.c2p(0, 0), plane.c2p(3, 2), buff=0) 

3402 self.add(plane.add_coordinates(), arrow.set_color(m.YELLOW)) 

3403 ``` 

3404 """ 

3405 

3406 def __init__( 

3407 self, 

3408 x_range: Sequence[float] | None = None, 

3409 y_range: Sequence[float] | None = None, 

3410 x_length: float | None = None, 

3411 y_length: float | None = None, 

3412 background_line_style: Style | None = None, 

3413 faded_line_style: Style | None = None, 

3414 faded_line_ratio: int = 1, 

3415 **kwargs: Unpack[AxesOptions], 

3416 ): 

3417 kwargs["axis_config"] = merged_axis_config( 

3418 { 

3419 "stroke_width": 2, 

3420 "include_ticks": False, 

3421 "include_tip": False, 

3422 "line_to_number_buff": SMALL_BUFF, 

3423 "label_direction": DR, 

3424 "font_size": 24, 

3425 }, 

3426 kwargs.get("axis_config"), 

3427 ) 

3428 kwargs["y_axis_config"] = merged_axis_config( 

3429 {"label_direction": DR}, kwargs.get("y_axis_config") 

3430 ) 

3431 # the frame as it is now: a tall video's (9:16) is taller than a wide one's 

3432 if x_range is None: 

3433 x_range = (-config.frame_x_radius, config.frame_x_radius, 1) 

3434 if y_range is None: 

3435 y_range = (-config.frame_y_radius, config.frame_y_radius, 1) 

3436 super().__init__( 

3437 background_line_style=background_line_style, 

3438 faded_line_style=faded_line_style, 

3439 faded_line_ratio=faded_line_ratio, 

3440 x_range=x_range, 

3441 y_range=y_range, 

3442 x_length=x_length, 

3443 y_length=y_length, 

3444 **kwargs, 

3445 ) 

3446 

3447 def _get_lines(self, faded_line_ratio: int) -> tuple[VGroup, VGroup]: 

3448 x_axis, y_axis = self.get_x_axis(), self.get_y_axis() 

3449 x_lines1, x_lines2 = self._get_lines_parallel_to_axis( 

3450 x_axis, y_axis, self.y_axis.x_range[2], faded_line_ratio 

3451 ) 

3452 y_lines1, y_lines2 = self._get_lines_parallel_to_axis( 

3453 y_axis, x_axis, self.x_axis.x_range[2], faded_line_ratio 

3454 ) 

3455 self.x_lines, self.y_lines = x_lines1, y_lines1 

3456 return VGroup(*x_lines1, *y_lines1), VGroup(*x_lines2, *y_lines2) 

3457 

3458 def _get_lines_parallel_to_axis( 

3459 self, 

3460 axis_parallel_to: NumberLine, 

3461 axis_perpendicular_to: NumberLine, 

3462 freq: float, 

3463 ratio_faded_lines: int, 

3464 ) -> tuple[VGroup, VGroup]: 

3465 line = Line(axis_parallel_to.get_start(), axis_parallel_to.get_end()) 

3466 ratio_faded_lines = ratio_faded_lines or 1 

3467 step = 1 / ratio_faded_lines * freq 

3468 lines1, lines2 = VGroup(), VGroup() 

3469 parts1: list[Line] = [] 

3470 parts2: list[Line] = [] 

3471 unit_vector_axis_perp_to = axis_perpendicular_to.get_unit_vector() 

3472 x_min, x_max, _ = axis_perpendicular_to.x_range 

3473 if axis_perpendicular_to.x_min > 0 and x_min < 0: 

3474 x_min, x_max = (0, np.abs(x_min) + np.abs(x_max)) 

3475 ranges = ( # (short of the edges, which no rounding of the steps puts a line on) 

3476 [0], 

3477 np.arange(step, min(x_max - x_min, x_max) - step * 1e-06, step), 

3478 np.arange(-step, max(x_min - x_max, x_min) + step * 1e-06, -step), 

3479 ) 

3480 for inputs in ranges: 

3481 for k, x in enumerate(inputs): 

3482 new_line = line.copy() 

3483 new_line.shift(unit_vector_axis_perp_to * x) 

3484 (parts1 if (k + 1) % ratio_faded_lines == 0 else parts2).append( 

3485 new_line 

3486 ) 

3487 lines1.add(*parts1) 

3488 lines2.add(*parts2) 

3489 return lines1, lines2 

3490 

3491 

3492type AzimuthUnits = Literal["PI radians", "TAU radians", "degrees", "gradians"] | None 

3493 

3494 

3495"""How a [PolarPlane][manimgx.PolarPlane] labels its angles: as fractions of π or of τ, 

3496in degrees, in gradians, or (None) as fractions of a turn.""" 

3497 

3498 

3499class PolarPlane(_Plane): 

3500 """A polar plane: circles around its origin, one at every step of the radius, and 

3501 lines out from it, a fraction of a turn apart; blue over white axes without ticks 

3502 or tips, unless styled. 

3503 

3504 The plane is a disc of radius `radius_max`, centered on the scene's origin, its x- 

3505 and y-axes its radii. [add_coordinates][manimgx.PolarPlane.add_coordinates] numbers 

3506 the radii and labels the lines' angles, in `azimuth_units`: fractions of π (3π/4), 

3507 of τ, degrees, gradians, or fractions of a turn. 

3508 [polar_to_point][manimgx.Axes.polar_to_point] (`pr2pt`) converts polar coordinates 

3509 to points, and [plot_polar_graph][manimgx.Axes.plot_polar_graph] plots curves 

3510 r = f(θ); everything [Axes][manimgx.Axes] do, the plane does. 

3511 

3512 Background styles and the faded-line ratio are construction inputs; the plane 

3513 retains its drawn grid rather than those setup attributes. 

3514 

3515 Args: 

3516 radius_max: The radius of the outer circle, in the plane's units; None for half 

3517 the frame's short side when the plane is made (4). 

3518 size: The plane's width, its diameter, in scene units; None for one scene unit 

3519 per unit. 

3520 radius_step: The distance between two circles, in the plane's units. 

3521 azimuth_step: How many lines divide the full turn: a line every turn divided 

3522 by it; None for the units' own: 20 for radians, 36 for degrees, 40 for 

3523 gradians, 1 for fractions of a turn. 

3524 azimuth_units: How the angles are labeled: `"PI radians"` (fractions of π), 

3525 `"TAU radians"` (fractions of τ), `"degrees"`, `"gradians"`, or None 

3526 (fractions of a turn, as decimals). 

3527 azimuth_compact_fraction: Whether a fraction of π or τ is written with the 

3528 constant in its numerator (3π/4), rather than after it (3/4 π). 

3529 azimuth_offset: The angle of the line labeled 0, in radians, counterclockwise 

3530 from the right: the lines and their labels turn with it. 

3531 azimuth_direction: The direction the angles increase in: `"CCW"`, 

3532 counterclockwise, or `"CW"`, clockwise. 

3533 azimuth_label_buff: The gap between the outer circle and the angles' labels, in 

3534 scene units. 

3535 azimuth_label_font_size: The font size of the angles' labels. 

3536 radius_config: [Number line keywords][manimgx.NumberLine] 

3537 for the radii's axes, over the plane's own (no ticks, no tips, 2 wide, 

3538 font size 24, numbers below and to the left); None for none. 

3539 background_line_style: [Style keywords][manimgx.drawing.paint.Style] for the 

3540 circles and lines, over their defaults: blue (`BLUE_D`), 2 wide, opaque; 

3541 None for none. 

3542 faded_line_style: [Style keywords][manimgx.drawing.paint.Style] for the fainter 

3543 circles and lines; None for the others' style, at half their width and 

3544 opacity. 

3545 faded_line_ratio: How many parts fainter circles and lines divide each step 

3546 into: 1 for none. 

3547 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the plane's group 

3548 itself: as it has no points, they do not restyle its lines. 

3549 

3550 Examples: 

3551 ```python 

3552 import manimgx as m 

3553 

3554 

3555 class PolarPlaneExample(m.Scene): 

3556 def construct(self) -> None: 

3557 planes = m.VGroup( 

3558 m.PolarPlane(radius_max=2, size=5.5, radius_step=0.5), 

3559 m.PolarPlane( 

3560 radius_max=2, 

3561 size=5.5, 

3562 azimuth_units="degrees", 

3563 azimuth_step=12, 

3564 faded_line_ratio=2, 

3565 ), 

3566 ) 

3567 for plane in planes: 

3568 plane.add_coordinates() 

3569 self.add(planes.arrange(buff=1.5)) 

3570 ``` 

3571 """ 

3572 

3573 def __init__( 

3574 self, 

3575 radius_max: float | None = None, 

3576 size: float | None = None, 

3577 radius_step: float = 1, 

3578 azimuth_step: float | None = None, 

3579 azimuth_units: AzimuthUnits = "PI radians", 

3580 azimuth_compact_fraction: bool = True, 

3581 azimuth_offset: float = 0, 

3582 azimuth_direction: Literal["CW", "CCW"] = "CCW", 

3583 azimuth_label_buff: float = SMALL_BUFF, 

3584 azimuth_label_font_size: float = 24, 

3585 radius_config: NumberLineOptions | None = None, 

3586 background_line_style: Style | None = None, 

3587 faded_line_style: Style | None = None, 

3588 faded_line_ratio: int = 1, 

3589 **kwargs: Unpack[Style], 

3590 ): 

3591 self.azimuth_units, self.azimuth_direction = azimuth_units, azimuth_direction 

3592 radius = ( 

3593 min(config.frame_x_radius, config.frame_y_radius) 

3594 if radius_max is None 

3595 else radius_max 

3596 ) 

3597 radius_config = merged_axis_config( 

3598 { 

3599 "stroke_width": 2, 

3600 "include_ticks": False, 

3601 "include_tip": False, 

3602 "line_to_number_buff": SMALL_BUFF, 

3603 "label_direction": DL, 

3604 "font_size": 24, 

3605 }, 

3606 radius_config, 

3607 ) 

3608 # Snapshot before assigning azimuth properties, which subclasses may override. 

3609 background_line_style = (background_line_style or Style()).copy() 

3610 default_steps = { 

3611 "PI radians": 20, 

3612 "TAU radians": 20, 

3613 "degrees": 36, 

3614 "gradians": 40, 

3615 None: 1, 

3616 } 

3617 self.azimuth_step = ( 

3618 default_steps[azimuth_units] if azimuth_step is None else azimuth_step 

3619 ) 

3620 self.azimuth_offset = azimuth_offset 

3621 self.azimuth_label_buff = azimuth_label_buff 

3622 self.azimuth_label_font_size = azimuth_label_font_size 

3623 self.azimuth_compact_fraction = azimuth_compact_fraction 

3624 super().__init__( 

3625 background_line_style=background_line_style, 

3626 faded_line_style=faded_line_style, 

3627 faded_line_ratio=faded_line_ratio, 

3628 x_range=(-radius, radius, radius_step), 

3629 y_range=(-radius, radius, radius_step), 

3630 x_length=size, 

3631 y_length=size, 

3632 axis_config=radius_config, 

3633 **kwargs, 

3634 ) 

3635 

3636 def _get_lines(self, faded_line_ratio: int) -> tuple[VGroup, VGroup]: 

3637 center = self.get_origin() 

3638 ratio_faded_lines = faded_line_ratio or 1 

3639 rstep = 1 / ratio_faded_lines * self.x_axis.x_range[2] 

3640 astep = 1 / ratio_faded_lines * (TAU * (1 / self.azimuth_step)) 

3641 rlines1, rlines2, alines1, alines2 = VGroup(), VGroup(), VGroup(), VGroup() 

3642 parts1: list[VMobject] = [] 

3643 parts2: list[VMobject] = [] 

3644 unit_vector = self.x_axis.get_unit_vector()[0] 

3645 # (the circles to the radius, the lines short of a whole turn: no rounding of the 

3646 # steps adds one beyond them) 

3647 for k, x in enumerate( 

3648 np.arange(0, self.x_axis.x_range[1] + rstep * 1e-06, rstep) 

3649 ): 

3650 (parts1 if k % ratio_faded_lines == 0 else parts2).append( 

3651 Circle(radius=x * unit_vector) 

3652 ) 

3653 alines1.add(*parts1) 

3654 alines2.add(*parts2) 

3655 parts1, parts2 = [], [] 

3656 line = Line(center, self.get_x_axis().get_end()) 

3657 for k, x in enumerate(np.arange(0, TAU - astep * 1e-06, astep)): 

3658 new_line = line.copy() 

3659 new_line.rotate(x + self.azimuth_offset, about_point=center) 

3660 (parts1 if k % ratio_faded_lines == 0 else parts2).append(new_line) 

3661 rlines1.add(*parts1) 

3662 rlines2.add(*parts2) 

3663 return VGroup(*rlines1, *alines1), VGroup(*rlines2, *alines2) 

3664 

3665 def get_coordinate_labels( 

3666 self, 

3667 r_values: Iterable[float] | None = None, 

3668 a_values: Iterable[float] | None = None, 

3669 ) -> VGroup: 

3670 """Number the plane's radii, and make labels for its angles. 

3671 

3672 The radii are numbered along the x-axis, right of the center; the numbers are 

3673 added to the axis. The angles' labels, in the plane's `azimuth_units`, go around 

3674 the outer circle, `azimuth_label_buff` beyond it: placed for a plane centered on 

3675 the scene's origin, as it is made. 

3676 

3677 Args: 

3678 r_values: The radii to number, in the plane's units; None for every 

3679 circle's but 0. 

3680 a_values: The angles to label, as fractions of a turn (0.25 is a quarter 

3681 turn); None for every line's. 

3682 

3683 Returns: 

3684 A new group of the x-axis, now numbered, and a group of the angles' labels 

3685 (not added to the plane); kept as the plane's `coordinate_labels`. 

3686 """ 

3687 if r_values is None: 

3688 r_values = [r for r in self.get_x_axis().get_tick_range() if r >= 0] 

3689 if a_values is None: 

3690 a_values = np.arange(0, 1, 1 / self.azimuth_step) 

3691 r_mobs = self.get_x_axis().add_numbers(r_values) 

3692 d = 1 if self.azimuth_direction == "CCW" else -1 

3693 radius = self.get_right()[0] 

3694 labels = VGroup() 

3695 for i in a_values: 

3696 angle = d * (i * TAU) + self.azimuth_offset 

3697 point = np.array([radius * np.cos(angle), radius * np.sin(angle), 0]) 

3698 label = self._azimuth_label(i) 

3699 labels.add( 

3700 label.next_to( 

3701 point, 

3702 direction=point, 

3703 aligned_edge=point, 

3704 buff=self.azimuth_label_buff, 

3705 ) 

3706 ) 

3707 self.coordinate_labels = VGroup(r_mobs, labels) 

3708 return self.coordinate_labels 

3709 

3710 def _azimuth_label(self, turns: float) -> MathTex: 

3711 """The label of the direction `turns` of a full turn, in the plane's units.""" 

3712 size = self.azimuth_label_font_size 

3713 match self.azimuth_units: 

3714 case "PI radians" | "TAU radians": 

3715 return self.get_radian_label(turns, font_size=size) 

3716 case "degrees": 

3717 return MathTex(f"{360 * turns:g}" + "^{\\circ}", font_size=size) 

3718 case "gradians": 

3719 return MathTex(f"{400 * turns:g}" + "^{g}", font_size=size) 

3720 case _: 

3721 return MathTex(f"{turns:g}", font_size=size) 

3722 

3723 def add_coordinates( # ty: ignore[invalid-method-override] # CE's: a polar plane numbers radii and angles 

3724 self, 

3725 r_values: Iterable[float] | None = None, 

3726 a_values: Iterable[float] | None = None, 

3727 ) -> Self: 

3728 """Number the plane's radii along its x-axis, and label its angles around it, 

3729 as [get_coordinate_labels][manimgx.PolarPlane.get_coordinate_labels] makes them. 

3730 

3731 Args: 

3732 r_values: The radii to number, in the plane's units; None for every 

3733 circle's but 0. 

3734 a_values: The angles to label, as fractions of a turn (0.25 is a quarter 

3735 turn); None for every line's. 

3736 """ 

3737 self.add(self.get_coordinate_labels(r_values, a_values)) 

3738 return self 

3739 

3740 def get_radian_label( 

3741 self, number: float, **kwargs: Unpack[MathTexOptions] 

3742 ) -> MathTex: 

3743 """Make the label of an angle in radians: a fraction of π, or of τ if the 

3744 plane's units are `"TAU radians"`. 

3745 

3746 The fraction is the nearest with a denominator up to 100, written as the plane's 

3747 `azimuth_compact_fraction` says: 3π/4, or 3/4 π. 

3748 

3749 Args: 

3750 number: The angle, as a fraction of a turn (0.375 for 3π/4). 

3751 **kwargs: [Math keywords][manimgx.MathTex] 

3752 for the label; its font size is 24 unless given. 

3753 

3754 Returns: 

3755 A new [MathTex][manimgx.MathTex]. 

3756 """ 

3757 kwargs.setdefault("font_size", 24) 

3758 units = ( 

3759 self.azimuth_units 

3760 if self.azimuth_units in ("PI radians", "TAU radians") 

3761 else "PI radians" 

3762 ) 

3763 constant = {"PI radians": "\\pi", "TAU radians": "\\tau"}[units] 

3764 frac = fr.Fraction(number * {"PI radians": 2, "TAU radians": 1}[units]) 

3765 p, q = (frac := frac.limit_denominator(100)).numerator, frac.denominator 

3766 if p == 0: 

3767 string = "0" 

3768 elif q == 1: 

3769 string = constant if p == 1 else f"{p}{constant}" 

3770 elif self.azimuth_compact_fraction: 

3771 string = f"\\tfrac{{{'' if p == 1 else p}{constant}}}{{{q}}}" 

3772 else: 

3773 string = f"\\tfrac{{{p}}}{{{q}}}{constant}" 

3774 return MathTex(string, **kwargs) 

3775 

3776 

3777class ComplexPlane(NumberPlane): 

3778 """A complex plane: a [NumberPlane][manimgx.NumberPlane] whose points are complex 

3779 numbers, x + yi at the point of coordinates (x, y). 

3780 

3781 [number_to_point][manimgx.ComplexPlane.number_to_point] (`n2p`) and 

3782 [point_to_number][manimgx.ComplexPlane.point_to_number] (`p2n`) convert between 

3783 numbers and points, and [add_coordinates][manimgx.ComplexPlane.add_coordinates] 

3784 writes the real numbers along the x-axis and the imaginary ones (with `i`) along 

3785 the y-axis. A function of complex numbers maps the plane with 

3786 [apply_complex_function][manimgx.Mobject.apply_complex_function]. It takes the 

3787 arguments of a [NumberPlane][manimgx.NumberPlane], and does everything it does. 

3788 

3789 Examples: 

3790 ```python 

3791 import manimgx as m 

3792 

3793 

3794 class ComplexPlaneExample(m.Scene): 

3795 def construct(self) -> None: 

3796 plane = m.ComplexPlane(x_range=[-6.5, 6.5, 1]).add_coordinates() 

3797 self.add(plane) 

3798 for z, name in ((2 + 1j, "2+i"), (-3 - 2j, "-3-2i")): 

3799 dot = m.Dot(plane.n2p(z), radius=0.12, color=m.YELLOW) 

3800 self.add(dot, m.MathTex(name).next_to(dot, m.UR, buff=0.1)) 

3801 ``` 

3802 """ 

3803 

3804 def number_to_point(self, number: float | complex) -> Point3D: 

3805 """Convert a complex number to its point on the plane: x + yi to the point of 

3806 coordinates (x, y). 

3807 

3808 `n2p` is its short name. 

3809 

3810 Args: 

3811 number: The number; a real number is on the x-axis. 

3812 

3813 Returns: 

3814 The point, in scene coordinates. 

3815 """ 

3816 number = complex(number) 

3817 return self.coords_to_point(number.real, number.imag) 

3818 

3819 def point_to_number(self, point: Point3DLike) -> complex: 

3820 """Convert a point to the complex number at it: x + yi, for the point's 

3821 coordinates (x, y). 

3822 

3823 `p2n` is its short name. 

3824 

3825 Args: 

3826 point: The point, in scene coordinates. 

3827 """ 

3828 x, y = self.point_to_coords(point)[:2] 

3829 return complex(x, y) 

3830 

3831 n2p, p2n = number_to_point, point_to_number 

3832 

3833 def _get_default_coordinate_values(self) -> list[float | complex]: 

3834 x_numbers = [float(x) for x in self.get_x_axis().get_tick_range()] 

3835 y_numbers = [ 

3836 complex(0, y) for y in self.get_y_axis().get_tick_range() if y != 0 

3837 ] 

3838 return [*x_numbers, *y_numbers] 

3839 

3840 def get_coordinate_labels( 

3841 self, *numbers: float | complex, **kwargs: Unpack[DecimalNumberOptions] 

3842 ) -> VGroup: 

3843 """Make labels for numbers of the plane: a real number by its point on the 

3844 x-axis, an imaginary one, with `i`, by its point on the y-axis. 

3845 

3846 A number is written as its larger part: its imaginary part, by the y-axis, if 

3847 that is larger in size than its real part; its real part, by the x-axis, 

3848 otherwise. Each is written as the axis numbers its ticks (see 

3849 [get_number_mobject][manimgx.NumberLine.get_number_mobject]). 

3850 

3851 Args: 

3852 *numbers: The numbers to label; none for the ticks of both axes, but 0. 

3853 **kwargs: [Number keywords][manimgx.DecimalNumber] 

3854 for the labels: `font_size`, `num_decimal_places`, `color`, …. 

3855 

3856 Returns: 

3857 A new group of the labels, kept as the plane's `coordinate_labels`; not 

3858 added to the plane. 

3859 """ 

3860 self.coordinate_labels = VGroup() 

3861 for number in numbers or self._get_default_coordinate_values(): 

3862 z = complex(number) 

3863 if abs(z.imag) > abs(z.real): 

3864 self.coordinate_labels.add( 

3865 self.get_y_axis().get_number_mobject( 

3866 z.imag, **(kwargs | {"unit": "i"}) 

3867 ) 

3868 ) 

3869 else: 

3870 self.coordinate_labels.add( 

3871 self.get_x_axis().get_number_mobject(z.real, **kwargs) 

3872 ) 

3873 return self.coordinate_labels 

3874 

3875 def add_coordinates( # ty: ignore[invalid-method-override] # CE's: numbers, not per-axis values 

3876 self, *numbers: float | complex, **kwargs: Unpack[DecimalNumberOptions] 

3877 ) -> Self: 

3878 """Label numbers of the plane, as 

3879 [get_coordinate_labels][manimgx.ComplexPlane.get_coordinate_labels] makes the 

3880 labels, and add them to the plane. 

3881 

3882 Args: 

3883 *numbers: The numbers to label; none for the ticks of both axes, but 0. 

3884 **kwargs: [Number keywords][manimgx.DecimalNumber] 

3885 for the labels: `font_size`, `num_decimal_places`, `color`, …. 

3886 """ 

3887 self.add(self.get_coordinate_labels(*numbers, **kwargs)) 

3888 return self 

3889 

3890 

3891EPSILON = 0.0001 

3892 

3893 

3894"""How far from 1 probabilities may sum before a sample space adds the rest as a 

3895part.""" 

3896 

3897 

3898class SampleSpace(Rectangle): 

3899 """A sample space: a rectangle standing for all the outcomes, to divide into parts 

3900 whose areas are probabilities; dark grey, filled, with a thin light grey outline, 

3901 unless styled. 

3902 

3903 [divide_vertically][manimgx.SampleSpace.divide_vertically] splits it into vertical 

3904 strips, one per probability, from left to right, and keeps them as its 

3905 `vertical_parts`; 

3906 [get_division_along_dimension][manimgx.SampleSpace.get_division_along_dimension] 

3907 makes the parts of a division along either side, in either direction. Each part is 

3908 a sample space itself, which can be divided in turn. 

3909 

3910 Args: 

3911 height: Its height, in scene units. 

3912 width: Its width, in scene units. 

3913 default_label_scale_val: Accepted for Manim compatibility; ignored. 

3914 

3915 Examples: 

3916 ```python 

3917 import manimgx as m 

3918 

3919 

3920 class SampleSpaceExample(m.Scene): 

3921 def construct(self) -> None: 

3922 space = m.SampleSpace(width=6, height=5) 

3923 space.divide_vertically(0.4, colors=[m.BLUE_E, m.GREY_BROWN]) 

3924 rain, dry = space.vertical_parts 

3925 colors = [m.RED_E, m.TEAL_E] 

3926 rain.add(rain.get_division_along_dimension(0.7, 1, colors, m.DOWN)) 

3927 dry.add(dry.get_division_along_dimension(0.2, 1, colors, m.DOWN)) 

3928 rain_label = m.Text("rain").next_to(rain, m.DOWN) 

3929 dry_label = m.Text("dry").next_to(dry, m.DOWN) 

3930 self.add(space, rain_label, dry_label) 

3931 ``` 

3932 """ 

3933 

3934 defaults: ClassVar[Style] = { 

3935 "fill_color": DARK_GREY, 

3936 "fill_opacity": 1.0, 

3937 "stroke_width": 0.5, 

3938 "stroke_color": LIGHT_GREY, 

3939 } 

3940 

3941 def __init__( 

3942 self, 

3943 height: float = 3, 

3944 width: float = 3, 

3945 default_label_scale_val: float = 1, 

3946 **kwargs: Unpack[Style], 

3947 ): 

3948 super().__init__(height=height, width=width, **kwargs) 

3949 self.default_label_scale_val = default_label_scale_val 

3950 

3951 @deprecated("Manim CE's machinery: ManimGX calls it itself", category=None) 

3952 def complete_p_list(self, p_list: float | Iterable[float]) -> list[float]: 

3953 """The probabilities of a division, completed to sum to 1: the rest, 1 minus 

3954 their sum, is added as one more, unless it is within 0.0001 of 0. 

3955 

3956 Args: 

3957 p_list: A probability, or probabilities. 

3958 

3959 Returns: 

3960 A new list of the probabilities. 

3961 """ 

3962 new_p_list: list[float] = ( 

3963 list(p_list) if isinstance(p_list, Iterable) else [p_list] 

3964 ) 

3965 remainder = 1.0 - sum(new_p_list) 

3966 if abs(remainder) > EPSILON: 

3967 new_p_list.append(remainder) 

3968 return new_p_list 

3969 

3970 def get_division_along_dimension( 

3971 self, 

3972 p_list: float | Iterable[float], 

3973 dim: int, 

3974 colors: Sequence[ParsableManimColor], 

3975 vect: Vector3D, 

3976 ) -> VGroup: 

3977 """Make the parts that divide the sample space along a dimension, one per 

3978 probability, each that fraction of it. 

3979 

3980 The parts follow one another in the direction `vect`, from the space's edge 

3981 opposite it; they are colored along a gradient of `colors`, and each is a sample 

3982 space itself. 

3983 

3984 Args: 

3985 p_list: The probabilities: a part is added for the rest, if they sum to less 

3986 than 1. 

3987 dim: The dimension divided: 0 for the width, 1 for the height. 

3988 colors: The colors, a gradient over the parts. 

3989 vect: The direction the parts follow one another in. 

3990 

3991 Returns: 

3992 A new group of the parts, not added to the space. 

3993 """ 

3994 p_list_complete = self.complete_p_list(p_list) 

3995 last_point = self.get_critical_point(-vect) 

3996 parts = VGroup() 

3997 for factor, color in zip( 

3998 p_list_complete, color_gradient(colors, len(p_list_complete)), strict=True 

3999 ): 

4000 part = SampleSpace() 

4001 part.set_fill(color, 1) 

4002 part.replace(self, stretch=True) 

4003 part.stretch(factor, dim) 

4004 part.move_to(last_point, -vect) 

4005 last_point = part.get_critical_point(vect) 

4006 parts.add(part) 

4007 return parts 

4008 

4009 def get_vertical_division( 

4010 self, 

4011 p_list: float | Iterable[float], 

4012 colors: Sequence[ParsableManimColor] = (MAROON_B, YELLOW), 

4013 vect: Vector3D = RIGHT, 

4014 ) -> VGroup: 

4015 """Make vertical strips that divide the sample space, one per probability, from 

4016 left to right (see 

4017 [get_division_along_dimension][manimgx.SampleSpace.get_division_along_dimension]). 

4018 

4019 Args: 

4020 p_list: The probabilities, completed to sum to 1. 

4021 colors: The colors, a gradient over the strips. 

4022 vect: The direction the strips follow one another in: RIGHT, from the left. 

4023 

4024 Returns: 

4025 A new group of the strips, not added to the space. 

4026 """ 

4027 return self.get_division_along_dimension(p_list, 0, colors, vect) 

4028 

4029 def divide_vertically( 

4030 self, 

4031 p_list: float | Iterable[float], 

4032 colors: Sequence[ParsableManimColor] = (MAROON_B, YELLOW), 

4033 vect: Vector3D = RIGHT, 

4034 ) -> Self: 

4035 """Divide the sample space into vertical strips, one per probability, from left 

4036 to right: each is that fraction of its width. 

4037 

4038 The probabilities are completed to sum to 1. The strips are added to the space, 

4039 as one group, and kept as its `vertical_parts`. 

4040 

4041 Args: 

4042 p_list: A probability, or probabilities. 

4043 colors: The strips' colors: a gradient over them. 

4044 vect: The direction the strips follow one another in: RIGHT, from the left. 

4045 

4046 Examples: 

4047 ```python 

4048 import manimgx as m 

4049 

4050 

4051 class SampleSpaceDivideVerticallyExample(m.Scene): 

4052 def construct(self) -> None: 

4053 space = m.SampleSpace(width=9, height=4) 

4054 space.divide_vertically([0.25, 0.25], colors=[m.RED_E, m.GOLD_E]) 

4055 parts = space.vertical_parts 

4056 labels = [m.Text(n).move_to(p) for n, p in zip("ABC", parts)] 

4057 self.add(space, *labels) 

4058 ``` 

4059 """ 

4060 self.vertical_parts = self.get_vertical_division(p_list, colors, vect) 

4061 self.add(self.vertical_parts) 

4062 return self 

4063 

4064 

4065class BarChart(Axes): 

4066 """A bar chart: a bar for each value, rising from the x-axis (or hanging below it, 

4067 for a negative value), on axes with a numbered y-axis; the bars colored along a 

4068 gradient. 

4069 

4070 Each bar stands in its own unit of the x-axis, centered in it and `bar_width` of it 

4071 wide, and it is as tall as its value, in the y-axis's units. The bars' names go 

4072 below the x-axis (above it, under a negative bar). 

4073 [change_bar_values][manimgx.BarChart.change_bar_values] changes the bars, and 

4074 [get_bar_labels][manimgx.BarChart.get_bar_labels] writes their values beside them. 

4075 The chart is [Axes][manimgx.Axes]: its x-axis runs from 0 to the number of bars. 

4076 

4077 Args: 

4078 values: The values, one bar each, from left to right. 

4079 bar_names: The bars' names, written by the x-axis, typeset as text; None for 

4080 none. 

4081 y_range: The y-axis's range, `[y_min, y_max, y_step]`; None to fit the values, 

4082 from 0 (or the lowest value, if negative) to the highest (or 0), with a step 

4083 of about one scene unit. Given two numbers, the step is that one. 

4084 x_length: The x-axis's length, in scene units; None for one scene unit per bar, 

4085 at most the frame's width less 2. 

4086 y_length: The y-axis's length, in scene units; None for 4, the frame's height 

4087 less 4. 

4088 bar_colors: The bars' colors: a gradient over them, from left to right. 

4089 bar_width: Each bar's width, as a fraction of its unit of the x-axis. 

4090 bar_fill_opacity: The bars' fill opacity, from 0 to 1. 

4091 bar_stroke_width: The width of the bars' outlines, in hundredths of a scene 

4092 unit. 

4093 **kwargs: [Axes keywords][manimgx.mobjects.plotting.AxesOptions]: 

4094 `x_axis_config` (over the chart's: numbers of size 24, typeset with 

4095 [Tex][manimgx.Tex]), `tips` (default False), …. 

4096 

4097 Examples: 

4098 ```python 

4099 import manimgx as m 

4100 

4101 

4102 class BarChartExample(m.Scene): 

4103 def construct(self) -> None: 

4104 chart = m.BarChart( 

4105 values=[-5, 40, -10, 20, -3], 

4106 bar_names=["one", "two", "three", "four", "five"], 

4107 y_range=[-20, 50, 10], 

4108 x_length=10, 

4109 y_length=6, 

4110 x_axis_config={"font_size": 36}, 

4111 ) 

4112 self.add(chart) 

4113 ``` 

4114 """ 

4115 

4116 def __init__( 

4117 self, 

4118 values: Sequence[float], 

4119 bar_names: Sequence[str] | None = None, 

4120 y_range: Sequence[float] | None = None, 

4121 x_length: float | None = None, 

4122 y_length: float | None = None, 

4123 bar_colors: Iterable[ParsableManimColor] = ( 

4124 "#003f5c", 

4125 "#58508d", 

4126 "#bc5090", 

4127 "#ff6361", 

4128 "#ffa600", 

4129 ), 

4130 bar_width: float = 0.6, 

4131 bar_fill_opacity: float = 0.7, 

4132 bar_stroke_width: float = 3, 

4133 **kwargs: Unpack[AxesOptions], 

4134 ): 

4135 y_length = y_length if y_length is not None else config.frame_height - 4 

4136 self.values = list(values) 

4137 """The chart's values, one per bar, as they are now.""" 

4138 self.bar_names = bar_names 

4139 self.bar_colors = list(bar_colors) 

4140 self.bar_width = bar_width 

4141 self.bar_fill_opacity = bar_fill_opacity 

4142 self.bar_stroke_width = bar_stroke_width 

4143 x_range = [0, len(self.values), 1] 

4144 if y_range is None: 

4145 y_range = [ 

4146 min(0, min(self.values)), 

4147 max(0, max(self.values)), 

4148 round(max(self.values) / y_length, 2), 

4149 ] 

4150 elif len(y_range) == 2: 

4151 y_range = [*y_range, round(max(self.values) / y_length, 2)] 

4152 if x_length is None: 

4153 x_length = min(len(self.values), config.frame_width - 2) 

4154 kwargs["x_axis_config"] = merged_axis_config( 

4155 {"font_size": 24, "label_constructor": Tex}, kwargs.get("x_axis_config") 

4156 ) 

4157 kwargs.setdefault("tips", False) 

4158 self.bars: VGroup = VGroup() 

4159 """The bars, rectangles, from left to right.""" 

4160 self.x_labels: VGroup | None = None 

4161 self.bar_labels: VGroup | None = None 

4162 super().__init__( 

4163 x_range=x_range, 

4164 y_range=y_range, 

4165 x_length=x_length, 

4166 y_length=y_length, 

4167 **kwargs, 

4168 ) 

4169 self._add_bars() 

4170 if self.bar_names is not None: 

4171 self._add_x_axis_labels() 

4172 self.y_axis.add_numbers() 

4173 

4174 def _update_colors(self) -> None: 

4175 self.bars.set_color_by_gradient(*self.bar_colors) 

4176 

4177 def _add_x_axis_labels(self) -> None: 

4178 if self.bar_names is None: 

4179 return 

4180 val_range = np.arange(0.5, len(self.bar_names), 1) 

4181 labels = VGroup() 

4182 for i, (value, bar_name) in enumerate( 

4183 zip(val_range, self.bar_names, strict=True) 

4184 ): 

4185 direction = UP if self.values[i] < 0 else DOWN 

4186 bar_name_label = self.x_axis.label_constructor(bar_name) 

4187 bar_name_label.font_size = self.x_axis.font_size 

4188 bar_name_label.next_to( 

4189 self.x_axis.number_to_point(value), 

4190 direction=direction, 

4191 buff=self.x_axis.line_to_number_buff, 

4192 ) 

4193 labels.add(bar_name_label) 

4194 self.x_axis.labels = labels 

4195 self.x_axis.add(labels) 

4196 

4197 def _create_bar(self, bar_number: int, value: float) -> Rectangle: 

4198 bar_h = abs(self.c2p(0, value)[1] - self.c2p(0, 0)[1]) 

4199 bar_w = self.c2p(self.bar_width, 0)[0] - self.c2p(0, 0)[0] 

4200 bar = Rectangle( 

4201 height=bar_h, 

4202 width=bar_w, 

4203 stroke_width=self.bar_stroke_width, 

4204 fill_opacity=self.bar_fill_opacity, 

4205 ) 

4206 pos = UP if value >= 0 else DOWN 

4207 bar.next_to(self.c2p(bar_number + 0.5, 0), pos, buff=0) 

4208 return bar 

4209 

4210 def _add_bars(self) -> None: 

4211 for i, value in enumerate(self.values): 

4212 tmp_bar = self._create_bar(bar_number=i, value=value) 

4213 self.bars.add(tmp_bar) 

4214 self._update_colors() 

4215 self.add_to_back(self.bars) 

4216 

4217 def get_bar_labels( 

4218 self, 

4219 color: ParsableManimColor | None = None, 

4220 font_size: float = 24, 

4221 buff: float = MED_SMALL_BUFF, 

4222 label_constructor: type[ManimTextLabel] = Tex, 

4223 ) -> VGroup: 

4224 """Make labels of the bars' values: each above its bar (below it, for a 

4225 negative value), in the bar's color unless given another. 

4226 

4227 Args: 

4228 color: The labels' color; None for each bar's fill color. 

4229 font_size: Their font size. 

4230 buff: The gap between each bar and its label, in scene units. 

4231 label_constructor: The class they are typeset with: [Tex][manimgx.Tex], 

4232 [MathTex][manimgx.MathTex], …. 

4233 

4234 Returns: 

4235 A new group of the labels, from left to right, not added to the chart. 

4236 

4237 Examples: 

4238 ```python 

4239 import manimgx as m 

4240 

4241 

4242 class BarChartGetBarLabelsExample(m.Scene): 

4243 def construct(self) -> None: 

4244 chart = m.BarChart( 

4245 values=[9, 7, 4, 3, 1], 

4246 y_range=[0, 10, 2], 

4247 x_length=10, 

4248 y_length=5, 

4249 bar_colors=[m.BLUE, m.GREEN, m.YELLOW], 

4250 ) 

4251 self.add(chart, chart.get_bar_labels(font_size=40)) 

4252 ``` 

4253 """ 

4254 bar_labels = VGroup() 

4255 for bar, value in zip(self.bars, self.values, strict=False): 

4256 bar_lbl = label_constructor(str(value)) 

4257 if color is None: 

4258 bar_lbl.set_color(bar.get_fill_color()) 

4259 else: 

4260 bar_lbl.set_color(color) 

4261 bar_lbl.font_size = font_size 

4262 pos = UP if value >= 0 else DOWN 

4263 bar_lbl.next_to(bar, pos, buff=buff) 

4264 bar_labels.add(bar_lbl) 

4265 return bar_labels 

4266 

4267 def change_bar_values( 

4268 self, values: Iterable[float], update_colors: bool = True 

4269 ) -> Self: 

4270 """Change the bars' values: each bar is stretched to its new height from the 

4271 x-axis, crossing to its other side if the value changes sign. 

4272 

4273 The y-axis stays as it is, and labels made before do not follow; to animate the 

4274 change, use `.animate`. 

4275 

4276 Args: 

4277 values: The new values, from left to right; fewer than the bars change the 

4278 first ones only. 

4279 update_colors: Whether to color the bars along the chart's gradient again (a 

4280 bar remade from a value of 0 needs it). 

4281 

4282 Examples: 

4283 ```python 

4284 import manimgx as m 

4285 

4286 

4287 class BarChartChangeBarValuesExample(m.Scene): 

4288 def construct(self) -> None: 

4289 chart = m.BarChart( 

4290 values=[4, 8, 2, 6], y_range=[-4, 8, 2], x_length=9, y_length=6 

4291 ) 

4292 self.add(chart) 

4293 self.play(chart.animate.change_bar_values([7, -3, 5, 1])) 

4294 ``` 

4295 """ 

4296 values = list(values) 

4297 # the bars as they are: a bar remade below takes its place in `self.bars` 

4298 for i, (bar, value) in enumerate(zip(list(self.bars), values, strict=False)): 

4299 chart_val = self.values[i] 

4300 if chart_val == 0: # a bar of no height has no side to grow from: remade 

4301 self.bars.remove(bar) 

4302 self.bars.insert(i, self._create_bar(i, value)) 

4303 continue 

4304 bar_lim, aligned_edge = ( 

4305 (bar.get_bottom(), DOWN) if chart_val > 0 else (bar.get_top(), UP) 

4306 ) 

4307 quotient = value / chart_val 

4308 if quotient < 0: 

4309 aligned_edge = UP if chart_val > 0 else DOWN 

4310 bar.stretch_to_fit_height(abs(quotient) * bar.height) 

4311 bar.move_to(bar_lim, aligned_edge) 

4312 if update_colors: 

4313 self._update_colors() 

4314 self.values[: len(values)] = values 

4315 return self