Debian Codegraph @

pyvista/plotting/axes_assembly.py

raw
1 """Axes assembly module."""
2
3 from __future__ import annotations
4
5 from abc import abstractmethod
6 from collections.abc import Sequence
7 from functools import wraps
8 import itertools
9 from typing import TYPE_CHECKING
10 from typing import Any
11 from typing import Literal
12 from typing import NamedTuple
13 from typing import TypedDict
14 from typing import get_args
15
16 import numpy as np
17
18 import pyvista as pv
19 from pyvista import BoundsTuple
20 from pyvista import _vtk
21 from pyvista._deprecate_positional_args import _deprecate_positional_args
22 from pyvista.core import _validation
23 from pyvista.core._validation.validate import _validate_color_sequence
24 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
25 from pyvista.core.utilities.geometric_sources import AxesGeometrySource
26 from pyvista.core.utilities.geometric_sources import OrthogonalPlanesSource
27 from pyvista.core.utilities.geometric_sources import _AxisEnum
28 from pyvista.core.utilities.geometric_sources import _PartEnum
29 from pyvista.core.utilities.misc import _NameMixin
30 from pyvista.core.utilities.misc import _NoNewAttrMixin
31 from pyvista.core.utilities.misc import _reciprocal
32 from pyvista.core.utilities.misc import abstract_class
33 from pyvista.core.utilities.transformations import decomposition
34 from pyvista.plotting.actor import Actor
35 from pyvista.plotting.colors import Color
36 from pyvista.plotting.prop3d import Prop3D
37 from pyvista.plotting.prop3d import _Prop3DMixin
38 from pyvista.plotting.text import Label
39 from pyvista.plotting.text import TextProperty
40
41 if TYPE_CHECKING:
42 from collections.abc import Iterator
43 import sys
44
45 from pyvista.core._typing_core import MatrixLike
46 from pyvista.core._typing_core import NumpyArray
47 from pyvista.core._typing_core import TransformLike
48 from pyvista.core._typing_core import VectorLike
49 from pyvista.core.dataset import DataSet
50 from pyvista.plotting._typing import ColorLike
51
52 if sys.version_info >= (3, 11):
53 from typing import Unpack
54 else:
55 from typing_extensions import Unpack
56
57 ScaleModeOptions = Literal['default', 'anti_distortion']
58
59
60 class _AxesPropTuple(NamedTuple):
61 x_shaft: float | str | ColorLike
62 y_shaft: float | str | ColorLike
63 z_shaft: float | str | ColorLike
64 x_tip: float | str | ColorLike
65 y_tip: float | str | ColorLike
66 z_tip: float | str | ColorLike
67
68
69 class _OrthogonalPlanesKwargs(TypedDict):
70 bounds: VectorLike[float]
71 resolution: int | VectorLike[int]
72 normal_sign: Literal['+', '-'] | Sequence[str]
73
74
75 class _XYZTuple(NamedTuple):
76 x: Any
77 y: Any
78 z: Any
79
80
81 @abstract_class
82 class _XYZAssembly(
83 _NoNewAttrMixin,
84 DisableVtkSnakeCase,
85 _Prop3DMixin,
86 _NameMixin,
87 _vtk.vtkPropAssembly,
88 ):
89 DEFAULT_LABELS = _XYZTuple('X', 'Y', 'Z')
90
91 def __init__(
92 self,
93 *,
94 xyz_actors: tuple[Any, Any, Any],
95 xyz_label_actors: tuple[Any, Any, Any],
96 x_label,
97 y_label,
98 z_label,
99 labels,
100 label_color,
101 show_labels,
102 label_position,
103 label_size,
104 x_color,
105 y_color,
106 z_color,
107 position: VectorLike[float],
108 orientation: VectorLike[float],
109 origin: VectorLike[float],
110 scale: float | VectorLike[float],
111 user_matrix: MatrixLike[float] | None,
112 name: str | None = None,
113 ):
114 super().__init__()
115
116 def _make_xyz_tuple(xyz):
117 def _get_tuple(actor_or_actors):
118 return (
119 actor_or_actors if isinstance(actor_or_actors, tuple) else (actor_or_actors,)
120 )
121
122 actor_tuples = [_get_tuple(actors) for actors in xyz]
123 return _XYZTuple(*actor_tuples)
124
125 self._assembly_actors = _make_xyz_tuple(xyz_actors)
126 self._assembly_label_actors = _make_xyz_tuple(xyz_label_actors)
127
128 # Add all actors to assembly
129 for parts in (*self._assembly_actors, *self._assembly_label_actors):
130 for part in parts:
131 self.AddPart(part)
132
133 # Set colors
134 if x_color is None:
135 x_color = pv.global_theme.axes.x_color
136 if y_color is None:
137 y_color = pv.global_theme.axes.y_color
138 if z_color is None:
139 z_color = pv.global_theme.axes.z_color
140
141 self.x_color = x_color
142 self.y_color = y_color
143 self.z_color = z_color
144
145 # Set text labels
146 if labels is None:
147 self.x_label = self.DEFAULT_LABELS.x if x_label is None else x_label
148 self.y_label = self.DEFAULT_LABELS.y if y_label is None else y_label
149 self.z_label = self.DEFAULT_LABELS.z if z_label is None else z_label
150 else:
151 msg = (
152 "Cannot initialize '{}' and 'labels' properties together. "
153 'Specify one or the other, not both.'
154 )
155 if x_label is not None:
156 raise ValueError(msg.format('x_label'))
157 if y_label is not None:
158 raise ValueError(msg.format('y_label'))
159 if z_label is not None:
160 raise ValueError(msg.format('z_label'))
161 self.labels = labels
162 self.show_labels = show_labels
163 self.label_color = label_color
164 self.label_size = label_size
165 self.label_position = label_position
166
167 self.position = position
168 self.orientation = orientation
169 self.scale = scale # type: ignore[assignment]
170 self.origin = origin
171 self.user_matrix = user_matrix
172
173 self._name = name
174
175 @property
176 def parts(self):
177 collection = self.GetParts()
178 return tuple(collection.GetItemAsObject(i) for i in range(collection.GetNumberOfItems()))
179
180 @property
181 def _label_actor_iterator(self) -> Iterator[Label]:
182 return itertools.chain.from_iterable(self._assembly_label_actors)
183
184 def _post_set_update(self):
185 # Update prop3D attributes for all assembly parts
186 parts = self.parts
187 new_matrix = pv.array_from_vtkmatrix(self._prop3d.GetMatrix())
188 for part in parts:
189 if isinstance(part, (Prop3D, _Prop3DMixin)) and not np.array_equal(
190 part.user_matrix, new_matrix
191 ):
192 part.user_matrix = new_matrix
193
194 def _get_bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
195 return BoundsTuple(*self.GetBounds())
196
197 @property
198 def show_labels(self) -> bool: # numpydoc ignore=RT01
199 """Show or hide the text labels for the axes."""
200 return self._show_labels
201
202 @show_labels.setter
203 def show_labels(self, value: bool):
204 self._show_labels = value
205 for label in self._label_actor_iterator:
206 label.SetVisibility(value)
207
208 @property
209 @abstractmethod
210 def labels(self): # numpydoc ignore=RT01
211 """XYZ labels."""
212
213 @labels.setter
214 @abstractmethod
215 def labels(self, labels):
216 """XYZ labels."""
217
218 @property
219 @abstractmethod
220 def x_label(self): # numpydoc ignore=RT01
221 """Text label for the x-axis."""
222
223 @x_label.setter
224 @abstractmethod
225 def x_label(self, label):
226 """Text label for the x-axis."""
227
228 @property
229 @abstractmethod
230 def y_label(self): # numpydoc ignore=RT01
231 """Text label for the y-axis."""
232
233 @y_label.setter
234 @abstractmethod
235 def y_label(self, label):
236 """Text label for the y-axis."""
237
238 @property
239 @abstractmethod
240 def z_label(self): # numpydoc ignore=RT01
241 """Text label for the z-axis."""
242
243 @z_label.setter
244 @abstractmethod
245 def z_label(self, label):
246 """Text label for the z-axis."""
247
248 @property
249 @abstractmethod
250 def label_size(self): # numpydoc ignore=RT01
251 """Size of the text labels."""
252
253 @label_size.setter
254 @abstractmethod
255 def label_size(self, size):
256 """Size of the text labels."""
257
258 @property
259 @abstractmethod
260 def label_position(self): # numpydoc ignore=RT01
261 """Position of the text labels."""
262
263 @label_position.setter
264 @abstractmethod
265 def label_position(self, position):
266 """Position of the text labels."""
267
268 @property
269 def label_color(self) -> Color: # numpydoc ignore=RT01
270 """Color of the text labels."""
271 return self._label_color
272
273 @label_color.setter
274 def label_color(self, color: ColorLike):
275 valid_color = Color(color)
276 self._label_color = valid_color
277 for label in self._label_actor_iterator:
278 label.prop.color = valid_color
279
280 @property
281 @abstractmethod
282 def x_color(self): # numpydoc ignore=RT01
283 """Color of the x-axis actors."""
284
285 @x_color.setter
286 @abstractmethod
287 def x_color(self, color):
288 """Color of the x-axis actors."""
289
290 @property
291 @abstractmethod
292 def y_color(self): # numpydoc ignore=RT01
293 """Color of the y-axis actors."""
294
295 @y_color.setter
296 @abstractmethod
297 def y_color(self, color):
298 """Color of the y-axis actors."""
299
300 @property
301 @abstractmethod
302 def z_color(self): # numpydoc ignore=RT01
303 """Color of the z-axis actors."""
304
305 @z_color.setter
306 @abstractmethod
307 def z_color(self, color):
308 """Color of the z-axis actors."""
309
310
311 class AxesAssembly(_XYZAssembly):
312 """Assembly of arrow-style axes parts.
313
314 The axes may be used as a widget or added to a scene.
315
316 Parameters
317 ----------
318 shaft_type : str | DataSet, default: 'cylinder'
319 Shaft type for all axes. Can be any of the following:
320
321 - ``'cylinder'``
322 - ``'sphere'``
323 - ``'hemisphere'``
324 - ``'cone'``
325 - ``'pyramid'``
326 - ``'cube'``
327 - ``'octahedron'``
328
329 Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet` may be
330 specified. In this case, the dataset must be oriented such that it "points" in
331 the positive z direction.
332
333 shaft_radius : float | VectorLike[float], default: 0.025
334 Radius of the axes shafts.
335
336 shaft_length : float | VectorLike[float], default: 0.8
337 Length of the shaft for each axis.
338
339 tip_type : str | DataSet, default: 'cone'
340 Tip type for all axes. Can be any of the following:
341
342 - ``'cylinder'``
343 - ``'sphere'``
344 - ``'hemisphere'``
345 - ``'cone'``
346 - ``'pyramid'``
347 - ``'cube'``
348 - ``'octahedron'``
349
350 Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet` may be
351 specified. In this case, the dataset must be oriented such that it "points" in
352 the positive z direction.
353
354 tip_radius : float | VectorLike[float], default: 0.1
355 Radius of the axes tips.
356
357 tip_length : float | VectorLike[float], default: 0.2
358 Length of the tip for each axis.
359
360 symmetric_bounds : bool, default: False
361 Make the bounds of the axes symmetric. This is mainly for using the axes with
362 :func:`~pyvista.Renderer.add_orientation_widget` to ensure the axes rotate correctly
363 about the origin.
364
365 scale_mode : 'default', 'anti_distortion', default: 'default'
366 Mode used when scaling the axes.
367
368 - ``'default'``: Apply standard geometric scaling using ``'scale'`` factors. The full
369 assembly is scaled as a single object. If non-uniform scaling is used, the axes may
370 appear distorted.
371 - ``'anti_distortion'``: Apply corrective scaling to axes shafts and tips to ensure they
372 do not appear distorted. The shaft diameters, tip diameters, and tip lengths will all
373 be scaled to appear uniform.
374
375 .. versionadded:: 0.47
376
377 x_label : str, default: 'X'
378 Text label for the x-axis. Alternatively, set the label with :attr:`labels`.
379
380 y_label : str, default: 'Y'
381 Text label for the y-axis. Alternatively, set the label with :attr:`labels`.
382
383 z_label : str, default: 'Z'
384 Text label for the z-axis. Alternatively, set the label with :attr:`labels`.
385
386 labels : Sequence[str], optional,
387 Text labels for the axes. This is an alternative parameter to using
388 :attr:`x_label`, :attr:`y_label`, and :attr:`z_label` separately.
389
390 label_color : ColorLike, default: 'black'
391 Color of the text labels.
392
393 show_labels : bool, default: True
394 Show or hide the text labels.
395
396 label_position : float | VectorLike[float], optional
397 Position of the text labels along each axis. By default, the labels are
398 positioned at the ends of the shafts.
399
400 label_size : int, default: 50
401 Size of the text labels.
402
403 x_color : ColorLike | Sequence[ColorLike], optional
404 Color of the x-axis shaft and tip.
405
406 y_color : ColorLike | Sequence[ColorLike], optional
407 Color of the y-axis shaft and tip.
408
409 z_color : ColorLike | Sequence[ColorLike], optional
410 Color of the z-axis shaft and tip.
411
412 position : VectorLike[float], default: (0.0, 0.0, 0.0)
413 Position of the axes in space.
414
415 orientation : VectorLike[float], default: (0, 0, 0)
416 Orientation angles of the axes which define rotations about the
417 world's x-y-z axes. The angles are specified in degrees and in
418 x-y-z order. However, the actual rotations are applied in the
419 around the y-axis first, then the x-axis, and finally the z-axis.
420
421 origin : VectorLike[float], default: (0.0, 0.0, 0.0)
422 Origin of the axes. This is the point about which all rotations take place. The
423 rotations are defined by the :attr:`~pyvista.Prop3D.orientation`.
424
425 scale : VectorLike[float], default: (1.0, 1.0, 1.0)
426 Scaling factor applied to the axes.
427
428 user_matrix : MatrixLike[float], optional
429 A 4x4 transformation matrix applied to the axes. Defaults to the identity matrix.
430 The user matrix is the last transformation applied to the actor.
431
432 name : str, optional
433 The name of this assembly used when tracking on a plotter.
434
435 .. versionadded:: 0.45
436
437 See Also
438 --------
439 AxesAssemblySymmetric
440
441 :ref:`axes_objects_example`
442 Example showing different axes objects.
443
444 Examples
445 --------
446 .. pyvista-plot::
447 :force_static:
448
449 Add axes to a plot.
450
451 >>> import pyvista as pv
452 >>> axes = pv.AxesAssembly()
453 >>> pl = pv.Plotter()
454 >>> _ = pl.add_actor(axes)
455 >>> pl.show()
456
457 Customize the axes colors. Set each axis to a single color, or set the colors of
458 each shaft and tip separately with two colors.
459
460 >>> axes.x_color = ['cyan', 'blue']
461 >>> axes.y_color = ['magenta', 'red']
462 >>> axes.z_color = 'yellow'
463
464 Customize the label color too.
465
466 >>> axes.label_color = 'brown'
467
468 >>> pl = pv.Plotter()
469 >>> _ = pl.add_actor(axes)
470 >>> pl.show()
471
472 Create axes with custom geometry. Use pyramid shafts and hemisphere tips and
473 modify the lengths.
474
475 >>> axes = pv.AxesAssembly(
476 ... shaft_type='pyramid',
477 ... tip_type='hemisphere',
478 ... tip_length=0.1,
479 ... shaft_length=(0.5, 1.0, 1.5),
480 ... )
481 >>> pl = pv.Plotter()
482 >>> _ = pl.add_actor(axes)
483 >>> pl.show()
484
485 Position and orient the axes in space.
486
487 >>> axes = pv.AxesAssembly(position=(1.0, 2.0, 3.0), orientation=(10, 20, 30))
488 >>> pl = pv.Plotter()
489 >>> _ = pl.add_actor(axes)
490 >>> pl.show()
491
492 Scale the axes non-uniformly.
493
494 >>> axes = pv.AxesAssembly(scale=(2.0, 6.0, 10.0))
495 >>> pl = pv.Plotter()
496 >>> _ = pl.add_actor(axes)
497 >>> pl.show()
498
499 Note how the non-uniform scaling distorts the axes such that the tips all have different
500 lengths and the shafts are no longer cylindrical. Use the anti-distortion mode when
501 scaling to avoid this.
502
503 >>> axes.scale_mode = 'anti_distortion'
504 >>> pl = pv.Plotter()
505 >>> _ = pl.add_actor(axes)
506 >>> pl.show()
507
508 Add axes to the minimum extent of a mesh's bounds.
509
510 >>> mesh = pv.ParametricEllipsoid(xradius=6, yradius=3, zradius=1)
511
512 >>> scale = mesh.bounds_size
513 >>> position = (mesh.bounds.x_min, mesh.bounds.y_min, mesh.bounds.z_min)
514 >>> axes = pv.AxesAssembly(
515 ... position=position, scale=scale, scale_mode='anti_distortion'
516 ... )
517
518 >>> pl = pv.Plotter()
519 >>> _ = pl.add_mesh(mesh)
520 >>> _ = pl.add_actor(axes)
521 >>> pl.view_xy()
522 >>> pl.show()
523
524 Add the axes as a custom orientation widget with
525 :func:`~pyvista.Renderer.add_orientation_widget`.
526
527 >>> axes = pv.AxesAssembly(symmetric_bounds=True)
528
529 >>> pl = pv.Plotter()
530 >>> _ = pl.add_mesh(pv.Cone())
531 >>> _ = pl.add_orientation_widget(
532 ... axes,
533 ... viewport=(0, 0, 0.5, 0.5),
534 ... )
535 >>> pl.show()
536
537 """
538
539 def _init_actors_from_source(self, geometry_source: AxesGeometrySource):
540 # Init shaft and tip actors
541 self._shaft_actors: tuple[Actor, Actor, Actor] = (Actor(), Actor(), Actor())
542 self._tip_actors: tuple[Actor, Actor, Actor] = (Actor(), Actor(), Actor())
543 self._shaft_and_tip_actors = (*self._shaft_actors, *self._tip_actors)
544
545 # Init shaft and tip datasets
546 self._shaft_and_tip_geometry_source = geometry_source
547 # Get output without updating source, since source will be updated when setting actor scale
548 shaft_tip_datasets = self._shaft_and_tip_geometry_source._output
549 for actor, dataset in zip(self._shaft_and_tip_actors, shaft_tip_datasets, strict=True):
550 actor.mapper = pv.DataSetMapper(dataset=dataset)
551
552 def __init__(
553 self,
554 *,
555 shaft_type: AxesGeometrySource.GeometryTypes | DataSet = 'cylinder',
556 shaft_radius: float | VectorLike[float] = 0.025,
557 shaft_length: float | VectorLike[float] = 0.8,
558 tip_type: AxesGeometrySource.GeometryTypes | DataSet = 'cone',
559 tip_radius: float | VectorLike[float] = 0.1,
560 tip_length: float | VectorLike[float] = 0.2,
561 symmetric_bounds: bool = False,
562 scale_mode: ScaleModeOptions = 'default',
563 x_label: str | None = None,
564 y_label: str | None = None,
565 z_label: str | None = None,
566 labels: Sequence[str] | None = None,
567 label_color: ColorLike = 'black',
568 show_labels: bool = True,
569 label_position: float | VectorLike[float] | None = None,
570 label_size: int = 50,
571 x_color: ColorLike | Sequence[ColorLike] | None = None,
572 y_color: ColorLike | Sequence[ColorLike] | None = None,
573 z_color: ColorLike | Sequence[ColorLike] | None = None,
574 position: VectorLike[float] = (0.0, 0.0, 0.0),
575 orientation: VectorLike[float] = (0.0, 0.0, 0.0),
576 origin: VectorLike[float] = (0.0, 0.0, 0.0),
577 scale: float | VectorLike[float] = (1.0, 1.0, 1.0),
578 user_matrix: MatrixLike[float] | None = None,
579 name: str | None = None,
580 ):
581 self._scale_mode = scale_mode
582 # Init shaft and tip actors
583 source = AxesGeometrySource(
584 shaft_type=shaft_type,
585 shaft_radius=shaft_radius,
586 shaft_length=shaft_length,
587 tip_type=tip_type,
588 tip_radius=tip_radius,
589 tip_length=tip_length,
590 symmetric_bounds=symmetric_bounds,
591 symmetric=False,
592 )
593 self._init_actors_from_source(source)
594 # Init label actors
595 self._label_actors = (Label(), Label(), Label())
596
597 _XYZAssembly.__init__(
598 self,
599 xyz_actors=tuple(zip(self._shaft_actors, self._tip_actors, strict=True)), # type: ignore[arg-type]
600 xyz_label_actors=self._label_actors,
601 x_label=x_label,
602 y_label=y_label,
603 z_label=z_label,
604 labels=labels,
605 label_color=label_color,
606 show_labels=show_labels,
607 label_position=label_position,
608 label_size=label_size,
609 x_color=x_color,
610 y_color=y_color,
611 z_color=z_color,
612 position=position,
613 orientation=orientation,
614 origin=origin,
615 scale=scale,
616 user_matrix=user_matrix,
617 name=name,
618 )
619 self._set_default_label_props()
620
621 def _set_default_label_props(self):
622 # TODO: implement set_text_prop() and use that instead
623 for label in self._label_actor_iterator:
624 prop = label.prop
625 prop.bold = True
626 prop.italic = True
627 prop.enable_shadow()
628 prop.SetShadowOffset(-1, 1)
629
630 def __repr__(self):
631 """Representation of the axes assembly."""
632 mat_info = 'Identity' if np.array_equal(self.user_matrix, np.eye(4)) else 'Set'
633 bnds = self.bounds
634
635 geometry_repr = repr(self._shaft_and_tip_geometry_source).splitlines()[1:]
636
637 attr = [
638 f'{type(self).__name__} ({hex(id(self))})',
639 *geometry_repr,
640 f" X label: '{self.x_label}'",
641 f" Y label: '{self.y_label}'",
642 f" Z label: '{self.z_label}'",
643 f' Label color: {self.label_color}',
644 f' Show labels: {self.show_labels}',
645 f' Label position: {self.label_position}',
646 ' X Color: ',
647 f' Shaft {self.x_color[0]}',
648 f' Tip {self.x_color[1]}',
649 ' Y Color: ',
650 f' Shaft {self.y_color[0]}',
651 f' Tip {self.y_color[1]}',
652 ' Z Color: ',
653 f' Shaft {self.z_color[0]}',
654 f' Tip {self.z_color[1]}',
655 f' Position: {self.position}',
656 f' Orientation: {self.orientation}',
657 f' Origin: {self.origin}',
658 f' Scale: {self.scale}',
659 f' User matrix: {mat_info}',
660 f' X Bounds {bnds.x_min:.3E}, {bnds.x_max:.3E}',
661 f' Y Bounds {bnds.y_min:.3E}, {bnds.y_max:.3E}',
662 f' Z Bounds {bnds.z_min:.3E}, {bnds.z_max:.3E}',
663 ]
664 return '\n'.join(attr)
665
666 @property
667 @wraps(AxesGeometrySource.shaft_length.fget) # type: ignore[attr-defined]
668 def shaft_length(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
669 """Wrap AxesGeometrySource."""
670 return self._shaft_and_tip_geometry_source.shaft_length
671
672 @shaft_length.setter
673 @wraps(AxesGeometrySource.shaft_length.fset) # type: ignore[attr-defined]
674 def shaft_length(self, length: float | VectorLike[float]) -> None:
675 """Wrap AxesGeometrySource."""
676 self._shaft_and_tip_geometry_source.shaft_length = length
677 self._shaft_and_tip_geometry_source.update()
678
679 @property
680 @wraps(AxesGeometrySource.tip_length.fget) # type: ignore[attr-defined]
681 def tip_length(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
682 """Wrap AxesGeometrySource."""
683 return self._shaft_and_tip_geometry_source.tip_length
684
685 @tip_length.setter
686 @wraps(AxesGeometrySource.tip_length.fset) # type: ignore[attr-defined]
687 def tip_length(self, length: float | VectorLike[float]) -> None:
688 """Wrap AxesGeometrySource."""
689 self._shaft_and_tip_geometry_source.tip_length = length
690 self._shaft_and_tip_geometry_source.update()
691
692 @property
693 @wraps(AxesGeometrySource.shaft_radius.fget) # type: ignore[attr-defined]
694 def shaft_radius(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
695 """Wrap AxesGeometrySource."""
696 return self._shaft_and_tip_geometry_source.shaft_radius
697
698 @shaft_radius.setter
699 @wraps(AxesGeometrySource.shaft_radius.fset) # type: ignore[attr-defined]
700 def shaft_radius(self, radius: float | VectorLike[float]) -> None:
701 """Wrap AxesGeometrySource."""
702 self._shaft_and_tip_geometry_source.shaft_radius = radius
703 self._shaft_and_tip_geometry_source.update()
704
705 @property
706 @wraps(AxesGeometrySource.tip_radius.fget) # type: ignore[attr-defined]
707 def tip_radius(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
708 """Wrap AxesGeometrySource."""
709 return self._shaft_and_tip_geometry_source.tip_radius
710
711 @tip_radius.setter
712 @wraps(AxesGeometrySource.tip_radius.fset) # type: ignore[attr-defined]
713 def tip_radius(self, radius: float | VectorLike[float]) -> None:
714 """Wrap AxesGeometrySource."""
715 self._shaft_and_tip_geometry_source.tip_radius = radius
716 self._shaft_and_tip_geometry_source.update()
717
718 @property
719 @wraps(AxesGeometrySource.shaft_type.fget) # type: ignore[attr-defined]
720 def shaft_type(self) -> str: # numpydoc ignore=RT01
721 """Wrap AxesGeometrySource."""
722 return self._shaft_and_tip_geometry_source.shaft_type
723
724 @shaft_type.setter
725 @wraps(AxesGeometrySource.shaft_type.fset) # type: ignore[attr-defined]
726 def shaft_type(self, shaft_type: AxesGeometrySource.GeometryTypes | DataSet) -> None:
727 """Wrap AxesGeometrySource."""
728 self._shaft_and_tip_geometry_source.shaft_type = shaft_type
729 self._shaft_and_tip_geometry_source.update()
730
731 @property
732 @wraps(AxesGeometrySource.tip_type.fget) # type: ignore[attr-defined]
733 def tip_type(self) -> str: # numpydoc ignore=RT01
734 """Wrap AxesGeometrySource."""
735 return self._shaft_and_tip_geometry_source.tip_type
736
737 @tip_type.setter
738 @wraps(AxesGeometrySource.tip_type.fset) # type: ignore[attr-defined]
739 def tip_type(self, tip_type: AxesGeometrySource.GeometryTypes | DataSet) -> None:
740 """Wrap AxesGeometrySource."""
741 self._shaft_and_tip_geometry_source.tip_type = tip_type
742 self._shaft_and_tip_geometry_source.update()
743
744 @property
745 @wraps(Prop3D.scale.fget) # type: ignore[attr-defined]
746 def scale(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
747 """Wrap Prop3D.scale."""
748 return _Prop3DMixin.scale.fget(self) # type: ignore[attr-defined]
749
750 @scale.setter
751 @wraps(Prop3D.scale.fset) # type: ignore[attr-defined]
752 def scale(self, scale: float | VectorLike[float]):
753 """Wrap Prop3D.scale."""
754 _Prop3DMixin.scale.fset(self, scale) # type: ignore[attr-defined]
755 self._update_scale()
756
757 @property
758 @wraps(Prop3D.user_matrix.fget) # type: ignore[attr-defined]
759 def user_matrix(self) -> NumpyArray[float]: # numpydoc ignore=RT01
760 """Wrap Prop3D.user_matrix."""
761 return _Prop3DMixin.user_matrix.fget(self) # type: ignore[attr-defined]
762
763 @user_matrix.setter
764 @wraps(Prop3D.user_matrix.fset) # type: ignore[attr-defined]
765 def user_matrix(self, value: TransformLike) -> None:
766 """Wrap Prop3D.user_matrix."""
767 _Prop3DMixin.user_matrix.fset(self, value) # type: ignore[attr-defined]
768 self._update_scale()
769
770 @property
771 def scale_mode(self) -> ScaleModeOptions: # numpydoc ignore=RT01
772 """Set or return the scaling mode.
773
774 - ``'default'``: Apply standard geometric scaling using :attr:`scale` factors. The full
775 assembly is scaled as a single object. If non-uniform scaling is used, the axes may
776 appear distorted.
777 - ``'anti_distortion'``: Apply corrective scaling to axes shafts and tips to ensure they
778 do not appear distorted. The shaft diameters, tip diameters, and tip lengths will all
779 be scaled to appear uniform. The corrective scaling applies to :attr:`scale` as well as
780 any scaling from :attr:`user_matrix`.
781
782 .. versionadded:: 0.47
783
784 """
785 return self._scale_mode
786
787 @scale_mode.setter
788 def scale_mode(self, mode: ScaleModeOptions) -> None:
789 self._scale_mode = mode
790 self._update_scale()
791
792 @property
793 def _scale_mode(self) -> ScaleModeOptions: # numpydoc ignore=RT01
794 return self.__scale_mode
795
796 @_scale_mode.setter
797 def _scale_mode(self, mode: ScaleModeOptions) -> None:
798 _validation.check_contains(
799 get_args(ScaleModeOptions), must_contain=mode, name='scale mode'
800 )
801 self.__scale_mode = mode
802
803 def _update_scale(self):
804 if self.scale_mode == 'anti_distortion':
805 _, _, _, scale, _ = decomposition(self._transformation_matrix)
806 # We "undo" anisotropic scaling by the actor, and apply uniform scaling
807 # instead using the geometric mean
808 geometric_mean = np.array(np.cbrt(np.prod(scale)))
809 factor = geometric_mean * _reciprocal(scale)
810 else:
811 factor = np.ones(shape=(3,), dtype=float)
812
813 source = self._shaft_and_tip_geometry_source
814 source._anti_distortion_factor = factor
815 source.update()
816 self._update_label_positions()
817
818 @property
819 def labels(self) -> tuple[str, str, str]: # numpydoc ignore=RT01
820 """Return or set the axes labels.
821
822 This property may be used as an alternative to using :attr:`x_label`,
823 :attr:`y_label`, and :attr:`z_label` separately.
824
825 Examples
826 --------
827 >>> import pyvista as pv
828 >>> axes_assembly = pv.AxesAssembly()
829 >>> axes_assembly.labels = ['X Axis', 'Y Axis', 'Z Axis']
830 >>> axes_assembly.labels
831 ('X Axis', 'Y Axis', 'Z Axis')
832
833 """
834 return self.x_label, self.y_label, self.z_label
835
836 @labels.setter
837 def labels(self, labels: list[str] | tuple[str, str, str]):
838 labels = _validate_label_sequence(labels, n_labels=3, name='labels')
839 self.x_label = labels[0]
840 self.y_label = labels[1]
841 self.z_label = labels[2]
842
843 @property
844 def x_label(self) -> str: # numpydoc ignore=RT01
845 """Text label for the x-axis.
846
847 Examples
848 --------
849 >>> import pyvista as pv
850 >>> axes_assembly = pv.AxesAssembly()
851 >>> axes_assembly.x_label = 'This axis'
852 >>> axes_assembly.x_label
853 'This axis'
854
855 """
856 return self._label_actors[0].input
857
858 @x_label.setter
859 def x_label(self, label: str):
860 self._label_actors[0].input = label
861
862 @property
863 def y_label(self) -> str: # numpydoc ignore=RT01
864 """Text label for the y-axis.
865
866 Examples
867 --------
868 >>> import pyvista as pv
869 >>> axes_assembly = pv.AxesAssembly()
870 >>> axes_assembly.y_label = 'This axis'
871 >>> axes_assembly.y_label
872 'This axis'
873
874 """
875 return self._label_actors[1].input
876
877 @y_label.setter
878 def y_label(self, label: str):
879 self._label_actors[1].input = label
880
881 @property
882 def z_label(self) -> str: # numpydoc ignore=RT01
883 """Text label for the z-axis.
884
885 Examples
886 --------
887 >>> import pyvista as pv
888 >>> axes_assembly = pv.AxesAssembly()
889 >>> axes_assembly.z_label = 'This axis'
890 >>> axes_assembly.z_label
891 'This axis'
892
893 """
894 return self._label_actors[2].input
895
896 @z_label.setter
897 def z_label(self, label: str):
898 self._label_actors[2].input = label
899
900 @property
901 def label_size(self) -> int: # numpydoc ignore=RT01
902 """Size of the text labels.
903
904 Must be a positive integer.
905 """
906 return self._label_size
907
908 @label_size.setter
909 def label_size(self, size: int):
910 self._label_size = size
911 for label in self._label_actor_iterator:
912 label.size = size
913
914 @property
915 def label_position(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
916 """Position of the text label along each axis.
917
918 By default, the labels are positioned at the ends of the shafts.
919
920 Values must be non-negative.
921
922 Examples
923 --------
924 >>> import pyvista as pv
925 >>> axes_assembly = pv.AxesAssembly()
926 >>> axes_assembly.label_position
927 (0.8, 0.8, 0.8)
928 >>> axes_assembly.label_position = 0.3
929 >>> axes_assembly.label_position
930 (0.3, 0.3, 0.3)
931 >>> axes_assembly.label_position = (0.1, 0.4, 0.2)
932 >>> axes_assembly.label_position
933 (0.1, 0.4, 0.2)
934
935 """
936 position = self._label_position
937 value = self._shaft_and_tip_geometry_source.shaft_length if position is None else position
938 if self.scale_mode == 'anti_distortion':
939 factor = self._shaft_and_tip_geometry_source._anti_distortion_factor
940 value += self.tip_length * (1 - factor)
941 return value
942
943 @label_position.setter
944 def label_position(self, position: float | VectorLike[float] | None):
945 self._label_position = (
946 None
947 if position is None
948 else _validation.validate_array3(
949 position,
950 broadcast=True,
951 must_be_in_range=[0, np.inf],
952 name='Label position',
953 dtype_out=float,
954 to_tuple=True,
955 )
956 )
957 self._update_label_positions()
958
959 @property
960 def x_color(self) -> tuple[Color, Color]: # numpydoc ignore=RT01
961 """Color of the x-axis shaft and tip."""
962 return self.get_actor_prop('color')[_AxisEnum.x :: 3]
963
964 @x_color.setter
965 def x_color(self, color: ColorLike | Sequence[ColorLike]):
966 self.set_actor_prop('color', color, axis=_AxisEnum.x.value) # type: ignore[arg-type]
967
968 @property
969 def y_color(self) -> tuple[Color, Color]: # numpydoc ignore=RT01
970 """Color of the y-axis shaft and tip."""
971 return self.get_actor_prop('color')[_AxisEnum.y :: 3]
972
973 @y_color.setter
974 def y_color(self, color: ColorLike | Sequence[ColorLike]):
975 self.set_actor_prop('color', color, axis=_AxisEnum.y.value) # type: ignore[arg-type]
976
977 @property
978 def z_color(self) -> tuple[Color, Color]: # numpydoc ignore=RT01
979 """Color of the z-axis shaft and tip."""
980 return self.get_actor_prop('color')[_AxisEnum.z.value :: 3]
981
982 @z_color.setter
983 def z_color(self, color: ColorLike | Sequence[ColorLike]):
984 self.set_actor_prop('color', color, axis=_AxisEnum.z.value) # type: ignore[arg-type]
985
986 @_deprecate_positional_args(allowed=['name', 'value'])
987 def set_actor_prop( # noqa: PLR0917
988 self,
989 name: str,
990 value: float | str | ColorLike | Sequence[float | str | ColorLike],
991 axis: Literal['x', 'y', 'z', 'all'] = 'all',
992 part: Literal['shaft', 'tip', 'all'] = 'all',
993 ):
994 """Set :class:`~pyvista.Property` attributes for the axes shaft and/or tip actors.
995
996 This is a generalized setter method which sets the value of a specific
997 :class:`~pyvista.Property` attribute for any combination of axis shaft or tip
998 parts.
999
1000 Parameters
1001 ----------
1002 name : str
1003 Name of the :class:`~pyvista.Property` attribute to set.
1004
1005 value : float | str | ColorLike | Sequence[float | str | ColorLike]
1006 Value to set the attribute to. If a single value, set all specified axes
1007 shaft(s) or tip(s) :class:`~pyvista.Property` attributes to this value.
1008 If a sequence of values, set the specified parts to these values.
1009
1010 axis : str | int, default: 'all'
1011 Set :class:`~pyvista.Property` attributes for a specific part of the axes.
1012 Specify one of:
1013
1014 - ``'x'``: only set the property for the x-axis.
1015 - ``'y'``: only set the property for the y-axis.
1016 - ``'z'``: only set the property for the z-axis.
1017 - ``'all'``: set the property for all three axes.
1018
1019 part : str | int, default: 'all'
1020 Set the property for a specific part of the axes. Specify one of:
1021
1022 - ``'shaft'``: only set the property for the axes shafts.
1023 - ``'tip'``: only set the property for the axes tips.
1024 - ``'all'``: set the property for axes shafts and tips.
1025
1026 Examples
1027 --------
1028 Set :attr:`~pyvista.Property.ambient` for all axes shafts and tips to a
1029 single value.
1030
1031 >>> import pyvista as pv
1032 >>> axes_assembly = pv.AxesAssembly()
1033 >>> axes_assembly.set_actor_prop('ambient', 0.7)
1034 >>> axes_assembly.get_actor_prop('ambient') # doctest: +NORMALIZE_WHITESPACE
1035 _AxesPropTuple(x_shaft=0.7,
1036 y_shaft=0.7,
1037 z_shaft=0.7,
1038 x_tip=0.7,
1039 y_tip=0.7,
1040 z_tip=0.7)
1041
1042 Set the property again, but this time set separate values for each part.
1043
1044 >>> values = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
1045 >>> axes_assembly.set_actor_prop('ambient', values)
1046 >>> axes_assembly.get_actor_prop('ambient') # doctest: +NORMALIZE_WHITESPACE
1047 _AxesPropTuple(x_shaft=0.1,
1048 y_shaft=0.2,
1049 z_shaft=0.3,
1050 x_tip=0.4,
1051 y_tip=0.5,
1052 z_tip=0.6)
1053
1054 Set :attr:`~pyvista.Property.opacity` for the x-axis only. The property is set
1055 for both the axis shaft and tip by default.
1056
1057 >>> axes_assembly.set_actor_prop('opacity', 0.5, axis='x')
1058 >>> axes_assembly.get_actor_prop('opacity') # doctest: +NORMALIZE_WHITESPACE
1059 _AxesPropTuple(x_shaft=0.5,
1060 y_shaft=1.0,
1061 z_shaft=1.0,
1062 x_tip=0.5,
1063 y_tip=1.0,
1064 z_tip=1.0)
1065
1066 Set the property again, but this time set separate values for the shaft and tip.
1067
1068 >>> axes_assembly.set_actor_prop('opacity', [0.3, 0.7], axis='x')
1069 >>> axes_assembly.get_actor_prop('opacity') # doctest: +NORMALIZE_WHITESPACE
1070 _AxesPropTuple(x_shaft=0.3,
1071 y_shaft=1.0,
1072 z_shaft=1.0,
1073 x_tip=0.7,
1074 y_tip=1.0,
1075 z_tip=1.0)
1076
1077 Set :attr:`~pyvista.Property.show_edges` for the axes shafts only. The property
1078 is set for all axes by default.
1079
1080 >>> axes_assembly.set_actor_prop('show_edges', True, part='shaft')
1081 >>> axes_assembly.get_actor_prop(
1082 ... 'show_edges'
1083 ... ) # doctest: +NORMALIZE_WHITESPACE
1084 _AxesPropTuple(x_shaft=True,
1085 y_shaft=True,
1086 z_shaft=True,
1087 x_tip=False,
1088 y_tip=False,
1089 z_tip=False)
1090
1091 Set the property again, but this time set separate values for each shaft.
1092
1093 >>> axes_assembly.set_actor_prop(
1094 ... 'show_edges', [True, False, True], part='shaft'
1095 ... )
1096 >>> axes_assembly.get_actor_prop(
1097 ... 'show_edges'
1098 ... ) # doctest: +NORMALIZE_WHITESPACE
1099 _AxesPropTuple(x_shaft=True,
1100 y_shaft=False,
1101 z_shaft=True,
1102 x_tip=False,
1103 y_tip=False,
1104 z_tip=False)
1105
1106 Set :attr:`~pyvista.Property.style` for a single axis and specific part.
1107
1108 >>> axes_assembly.set_actor_prop('style', 'wireframe', axis='x', part='shaft')
1109 >>> axes_assembly.get_actor_prop('style') # doctest: +NORMALIZE_WHITESPACE
1110 _AxesPropTuple(x_shaft='Wireframe',
1111 y_shaft='Surface',
1112 z_shaft='Surface',
1113 x_tip='Surface',
1114 y_tip='Surface',
1115 z_tip='Surface')
1116
1117 """
1118 actors = self._filter_part_actors(axis=axis, part=part)
1119 values: Sequence[float | str | ColorLike]
1120
1121 # Validate input as a sequence of values
1122 if 'color' in name:
1123 # Special case for color inputs
1124 if axis == 'all' and part == 'all':
1125 n_values = 6
1126 elif part == 'all':
1127 n_values = 2
1128 elif axis == 'all':
1129 n_values = 3
1130 else:
1131 n_values = 1
1132 values = _validate_color_sequence(value, n_values) # type: ignore[arg-type]
1133 elif isinstance(value, Sequence) and not isinstance(value, str):
1134 # Number sequence
1135 values = value
1136 else:
1137 # Scalar number or string
1138 values = [value] * len(actors)
1139
1140 if len(values) != len(actors):
1141 msg = (
1142 f'Number of values ({len(values)}) in {value} must match the number of '
1143 f"actors ({len(actors)}) for axis '{axis}' and part '{part}'"
1144 )
1145 raise ValueError(msg)
1146
1147 # Sequence is valid, now set values
1148 for actor, val in zip(actors, values, strict=True):
1149 setattr(actor.prop, name, val)
1150
1151 def get_actor_prop(self, name: str):
1152 """Get :class:`~pyvista.Property` attributes for the axes shaft and/or tip actors.
1153
1154 This is a generalized getter method which returns the value of
1155 a specific :class:`pyvista.Property` attribute for all shafts and tips.
1156
1157 Parameters
1158 ----------
1159 name : str
1160 Name of the :class:`~pyvista.Property` attribute to get.
1161
1162 Returns
1163 -------
1164 tuple
1165 Named tuple with attribute values for the axes shafts and tips.
1166 The values are ordered ``(x_shaft, y_shaft, z_shaft, x_tip, y_tip, z_tip)``.
1167
1168 Examples
1169 --------
1170 Get the ambient property of the axes shafts and tips.
1171
1172 >>> import pyvista as pv
1173 >>> axes_assembly = pv.AxesAssembly()
1174 >>> axes_assembly.get_actor_prop('ambient')
1175 _AxesPropTuple(x_shaft=0.0, y_shaft=0.0, z_shaft=0.0, x_tip=0.0, y_tip=0.0, z_tip=0.0)
1176
1177 """
1178 prop_values = [getattr(actor.prop, name) for actor in self._shaft_and_tip_actors]
1179 return _AxesPropTuple(*prop_values)
1180
1181 def _filter_part_actors(
1182 self,
1183 axis: Literal['x', 'y', 'z', 'all'] = 'all',
1184 part: Literal['shaft', 'tip', 'all'] = 'all',
1185 ):
1186 valid_axis = [0, 1, 2, 'x', 'y', 'z', 'all']
1187 valid_axis_official = valid_axis[3:]
1188 if axis not in valid_axis:
1189 msg = f'Axis must be one of {valid_axis_official}.'
1190 raise ValueError(msg)
1191 valid_part = [0, 1, 'shaft', 'tip', 'all']
1192 valid_part_official = valid_part[2:]
1193 if part not in valid_part:
1194 msg = f'Part must be one of {valid_part_official}.'
1195 raise ValueError(msg)
1196
1197 # Create ordered list of filtered actors
1198 # Iterate over parts in <shaft-xyz> then <tip-xyz> order
1199 actors: list[Actor] = []
1200 for part_type, axis_num in itertools.product(_PartEnum, _AxisEnum):
1201 if part in [part_type.name, part_type.value, 'all'] and axis in [
1202 axis_num.name,
1203 axis_num.value,
1204 'all',
1205 ]:
1206 # Add actor to list
1207 if part_type == _PartEnum.shaft:
1208 actors.append(self._shaft_actors[axis_num])
1209 else:
1210 actors.append(self._tip_actors[axis_num])
1211
1212 return actors
1213
1214 def _get_offset_label_position_vectors(self, position_scalars):
1215 position_vectors = np.diag(position_scalars)
1216
1217 tip_radius = self.tip_radius
1218 factor = self._shaft_and_tip_geometry_source._anti_distortion_factor
1219 for axis in range(3):
1220 # Set radial (off-axis) values
1221 for r in [i for i in range(3) if i != axis]:
1222 position_vectors[axis, r] += tip_radius[r] * factor[r]
1223
1224 return position_vectors
1225
1226 def _update_label_positions(self):
1227 labels = self._label_actors
1228 position_vectors = self._get_offset_label_position_vectors(self.label_position)
1229 for label, position in zip(labels, position_vectors, strict=True):
1230 label.relative_position = position
1231
1232
1233 def _validate_label_sequence(labels: Sequence[str], n_labels: int | Sequence[int], name: str):
1234 _validation.check_instance(labels, (list, tuple), name=name)
1235 _validation.check_iterable_items(labels, str, name=name)
1236 _validation.check_length(labels, exact_length=n_labels, name=name)
1237 return labels
1238
1239
1240 class AxesAssemblySymmetric(AxesAssembly):
1241 """Symmetric assembly of arrow-style axes parts.
1242
1243 This class is similar to :class:`~pyvista.AxesAssembly` but the axes are
1244 symmetric.
1245
1246 The axes may be used as a widget or added to a scene.
1247
1248 Parameters
1249 ----------
1250 shaft_type : str | DataSet, default: 'cylinder'
1251 Shaft type for all axes. Can be any of the following:
1252
1253 - ``'cylinder'``
1254 - ``'sphere'``
1255 - ``'hemisphere'``
1256 - ``'cone'``
1257 - ``'pyramid'``
1258 - ``'cube'``
1259 - ``'octahedron'``
1260
1261 Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet` may be
1262 specified. In this case, the dataset must be oriented such that it "points" in
1263 the positive z direction.
1264
1265 shaft_radius : float | VectorLike[float], default: 0.025
1266 Radius of the axes shafts.
1267
1268 shaft_length : float | VectorLike[float], default: 0.8
1269 Length of the shaft for each axis.
1270
1271 tip_type : str | DataSet, default: 'cone'
1272 Tip type for all axes. Can be any of the following:
1273
1274 - ``'cylinder'``
1275 - ``'sphere'``
1276 - ``'hemisphere'``
1277 - ``'cone'``
1278 - ``'pyramid'``
1279 - ``'cube'``
1280 - ``'octahedron'``
1281
1282 Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet` may be
1283 specified. In this case, the dataset must be oriented such that it "points" in
1284 the positive z direction.
1285
1286 tip_radius : float | VectorLike[float], default: 0.1
1287 Radius of the axes tips.
1288
1289 tip_length : float | VectorLike[float], default: 0.2
1290 Length of the tip for each axis.
1291
1292 scale_mode : 'default', 'anti_distortion', default: 'default'
1293 Mode used when scaling the axes.
1294
1295 - ``'default'``: Apply standard geometric scaling using ``'scale'`` factors. The full
1296 assembly is scaled as a single object. If non-uniform scaling is used, the axes may
1297 appear distorted.
1298 - ``'anti_distortion'``: Apply corrective scaling to axes shafts and tips to ensure they
1299 do not appear distorted. The shaft diameters, tip diameters, and tip lengths will all
1300 be scaled to appear uniform.
1301
1302 .. versionadded:: 0.47
1303
1304 x_label : str, default: ('+X', '-X')
1305 Text labels for the positive and negative x-axis. Specify two strings or a
1306 single string. If a single string, plus ``'+'`` and minus ``'-'`` characters
1307 are added. Alternatively, set the labels with :attr:`labels`.
1308
1309 y_label : str, default: ('+Y', '-Y')
1310 Text labels for the positive and negative y-axis. Specify two strings or a
1311 single string. If a single string, plus ``'+'`` and minus ``'-'`` characters
1312 are added. Alternatively, set the labels with :attr:`labels`.
1313
1314 z_label : str, default: ('+Z', '-Z')
1315 Text labels for the positive and negative z-axis. Specify two strings or a
1316 single string. If a single string, plus ``'+'`` and minus ``'-'`` characters
1317 are added. Alternatively, set the labels with :attr:`labels`.
1318
1319 labels : Sequence[str], optional
1320 Text labels for the axes. Specify three strings, one for each axis, or
1321 six strings, one for each +/- axis. If three strings plus ``'+'`` and minus
1322 ``'-'`` characters are added. This is an alternative parameter to using
1323 :attr:`x_label`, :attr:`y_label`, and :attr:`z_label` separately.
1324
1325 label_color : ColorLike, default: 'black'
1326 Color of the text labels.
1327
1328 show_labels : bool, default: True
1329 Show or hide the text labels.
1330
1331 label_position : float | VectorLike[float], optional
1332 Position of the text labels along each axis. By default, the labels are
1333 positioned at the ends of the shafts.
1334
1335 label_size : int, default: 50
1336 Size of the text labels.
1337
1338 x_color : ColorLike | Sequence[ColorLike], optional
1339 Color of the x-axis shaft and tip.
1340
1341 y_color : ColorLike | Sequence[ColorLike], optional
1342 Color of the y-axis shaft and tip.
1343
1344 z_color : ColorLike | Sequence[ColorLike], optional
1345 Color of the z-axis shaft and tip.
1346
1347 position : VectorLike[float], default: (0.0, 0.0, 0.0)
1348 Position of the axes in space.
1349
1350 orientation : VectorLike[float], default: (0, 0, 0)
1351 Orientation angles of the axes which define rotations about the
1352 world's x-y-z axes. The angles are specified in degrees and in
1353 x-y-z order. However, the actual rotations are applied in the
1354 around the y-axis first, then the x-axis, and finally the z-axis.
1355
1356 origin : VectorLike[float], default: (0.0, 0.0, 0.0)
1357 Origin of the axes. This is the point about which all rotations take place. The
1358 rotations are defined by the :attr:`~pyvista.Prop3D.orientation`.
1359
1360 scale : VectorLike[float], default: (1.0, 1.0, 1.0)
1361 Scaling factor applied to the axes.
1362
1363 user_matrix : MatrixLike[float], optional
1364 A 4x4 transformation matrix applied to the axes. Defaults to the identity matrix.
1365 The user matrix is the last transformation applied to the actor.
1366
1367 name : str, optional
1368 The name of this assembly used when tracking on a plotter.
1369
1370 .. versionadded:: 0.45
1371
1372 See Also
1373 --------
1374 AxesAssembly
1375
1376 :ref:`axes_objects_example`
1377 Example showing different axes objects.
1378
1379 Examples
1380 --------
1381 .. pyvista-plot::
1382 :force_static:
1383
1384 Add symmetric axes to a plot.
1385
1386 >>> import pyvista as pv
1387 >>> axes_assembly = pv.AxesAssemblySymmetric()
1388 >>> pl = pv.Plotter()
1389 >>> _ = pl.add_actor(axes_assembly)
1390 >>> pl.show()
1391
1392 Customize the axes labels.
1393
1394 >>> axes_assembly.labels = [
1395 ... 'east',
1396 ... 'west',
1397 ... 'north',
1398 ... 'south',
1399 ... 'up',
1400 ... 'down',
1401 ... ]
1402 >>> axes_assembly.label_color = 'darkgoldenrod'
1403
1404 >>> pl = pv.Plotter()
1405 >>> _ = pl.add_actor(axes_assembly)
1406 >>> pl.show()
1407
1408 Add the axes as a custom orientation widget with
1409 :func:`~pyvista.Renderer.add_orientation_widget`. We also configure the labels to
1410 only show text for the positive axes.
1411
1412 >>> axes_assembly = pv.AxesAssemblySymmetric(
1413 ... x_label=('X', ''), y_label=('Y', ''), z_label=('Z', '')
1414 ... )
1415 >>> pl = pv.Plotter()
1416 >>> _ = pl.add_mesh(pv.Cone())
1417 >>> _ = pl.add_orientation_widget(
1418 ... axes_assembly,
1419 ... viewport=(0, 0, 0.5, 0.5),
1420 ... )
1421 >>> pl.show()
1422
1423 """
1424
1425 def __init__(
1426 self,
1427 *,
1428 shaft_type: AxesGeometrySource.GeometryTypes | DataSet = 'cylinder',
1429 shaft_radius: float | VectorLike[float] = 0.025,
1430 shaft_length: float | VectorLike[float] = 0.8,
1431 tip_type: AxesGeometrySource.GeometryTypes | DataSet = 'cone',
1432 tip_radius: float | VectorLike[float] = 0.1,
1433 tip_length: float | VectorLike[float] = 0.2,
1434 scale_mode: ScaleModeOptions = 'default',
1435 x_label: str | Sequence[str] | None = None,
1436 y_label: str | Sequence[str] | None = None,
1437 z_label: str | Sequence[str] | None = None,
1438 labels: Sequence[str] | None = None,
1439 label_color: ColorLike = 'black',
1440 show_labels: bool = True,
1441 label_position: float | VectorLike[float] | None = None,
1442 label_size: int = 50,
1443 x_color: ColorLike | Sequence[ColorLike] | None = None,
1444 y_color: ColorLike | Sequence[ColorLike] | None = None,
1445 z_color: ColorLike | Sequence[ColorLike] | None = None,
1446 position: VectorLike[float] = (0.0, 0.0, 0.0),
1447 orientation: VectorLike[float] = (0.0, 0.0, 0.0),
1448 origin: VectorLike[float] = (0.0, 0.0, 0.0),
1449 scale: float | VectorLike[float] = (1.0, 1.0, 1.0),
1450 user_matrix: MatrixLike[float] | None = None,
1451 name: str | None = None,
1452 ):
1453 self._scale_mode = scale_mode
1454 # Init shaft and tip actors
1455 source = AxesGeometrySource(
1456 shaft_type=shaft_type,
1457 shaft_radius=shaft_radius,
1458 shaft_length=shaft_length,
1459 tip_type=tip_type,
1460 tip_radius=tip_radius,
1461 tip_length=tip_length,
1462 symmetric=True,
1463 )
1464 self._init_actors_from_source(source)
1465 # Init label actors
1466 self._label_actors = (Label(), Label(), Label())
1467 self._label_actors_symmetric = (Label(), Label(), Label())
1468
1469 _XYZAssembly.__init__(
1470 self,
1471 xyz_actors=tuple(zip(self._shaft_actors, self._tip_actors, strict=True)), # type: ignore[arg-type]
1472 xyz_label_actors=tuple(
1473 zip(self._label_actors, self._label_actors_symmetric, strict=True)
1474 ), # type: ignore[arg-type]
1475 x_label=x_label,
1476 y_label=y_label,
1477 z_label=z_label,
1478 labels=labels,
1479 label_color=label_color,
1480 show_labels=show_labels,
1481 label_position=label_position,
1482 label_size=label_size,
1483 x_color=x_color,
1484 y_color=y_color,
1485 z_color=z_color,
1486 position=position,
1487 orientation=orientation,
1488 origin=origin,
1489 scale=scale,
1490 user_matrix=user_matrix,
1491 name=name,
1492 )
1493 self._set_default_label_props()
1494
1495 @property # type: ignore[override]
1496 def labels(self) -> tuple[str, str, str, str, str, str]: # numpydoc ignore=RT01
1497 """Return or set the axes labels.
1498
1499 Specify three strings, one for each axis, or six strings, one for each +/- axis.
1500 If three strings, plus ``'+'`` and minus ``'-'`` characters are added.
1501 This property may be used as an alternative to using :attr:`x_label`,
1502 :attr:`y_label`, and :attr:`z_label` separately.
1503
1504 Examples
1505 --------
1506 >>> import pyvista as pv
1507 >>> axes_assembly = pv.AxesAssemblySymmetric()
1508
1509 Use three strings to set the labels. Plus ``'+'`` and minus ``'-'``
1510 characters are added automatically.
1511
1512 >>> axes_assembly.labels = ['U', 'V', 'W']
1513 >>> axes_assembly.labels
1514 ('+U', '-U', '+V', '-V', '+W', '-W')
1515
1516 Alternatively, use six strings to set the labels explicitly.
1517
1518 >>> axes_assembly.labels = [
1519 ... 'east',
1520 ... 'west',
1521 ... 'north',
1522 ... 'south',
1523 ... 'up',
1524 ... 'down',
1525 ... ]
1526 >>> axes_assembly.labels
1527 ('east', 'west', 'north', 'south', 'up', 'down')
1528
1529 """
1530 return *self.x_label, *self.y_label, *self.z_label
1531
1532 @labels.setter
1533 def labels(
1534 self,
1535 labels: list[str] | tuple[str, str, str] | tuple[str, str, str, str, str, str],
1536 ):
1537 valid_labels = _validate_label_sequence(labels, n_labels=[3, 6], name='labels')
1538 if len(valid_labels) == 3:
1539 self.x_label = valid_labels[0]
1540 self.y_label = valid_labels[1]
1541 self.z_label = valid_labels[2]
1542 else:
1543 self.x_label = valid_labels[0:2]
1544 self.y_label = valid_labels[2:4]
1545 self.z_label = valid_labels[4:6]
1546
1547 def _get_axis_label(self, axis: _AxisEnum) -> tuple[str, str]:
1548 label_plus = self._label_actors[axis].input
1549 label_minus = self._label_actors_symmetric[axis].input
1550 return label_plus, label_minus
1551
1552 def _set_axis_label(self, axis: _AxisEnum, label: str | list[str] | tuple[str, str]):
1553 if isinstance(label, str):
1554 label_plus, label_minus = '+' + label, '-' + label
1555 else:
1556 label_plus, label_minus = _validate_label_sequence(label, n_labels=2, name='label')
1557 self._label_actors[axis].input = label_plus
1558 self._label_actors_symmetric[axis].input = label_minus
1559
1560 @property # type: ignore[override]
1561 def x_label(self) -> tuple[str, str]: # numpydoc ignore=RT01
1562 """Return or set the labels for the positive and negative x-axis.
1563
1564 The labels may be set with a single string or two strings. If a single string,
1565 plus ``'+'`` and minus ``'-'`` characters are added. Alternatively, set the
1566 labels with :attr:`labels`.
1567
1568 Examples
1569 --------
1570 Set the labels with a single string. Plus ``'+'`` and minus ``'-'``
1571 characters are added automatically.
1572
1573 >>> import pyvista as pv
1574 >>> axes_assembly = pv.AxesAssemblySymmetric()
1575 >>> axes_assembly.x_label = 'Axis'
1576 >>> axes_assembly.x_label
1577 ('+Axis', '-Axis')
1578
1579 Set the labels explicitly with two strings.
1580
1581 >>> axes_assembly.x_label = 'anterior', 'posterior'
1582 >>> axes_assembly.x_label
1583 ('anterior', 'posterior')
1584
1585 """
1586 return self._get_axis_label(_AxisEnum.x)
1587
1588 @x_label.setter
1589 def x_label(self, label: str | list[str] | tuple[str, str]):
1590 self._set_axis_label(_AxisEnum.x, label)
1591
1592 @property # type: ignore[override]
1593 def y_label(self) -> tuple[str, str]: # numpydoc ignore=RT01
1594 """Return or set the labels for the positive and negative y-axis.
1595
1596 The labels may be set with a single string or two strings. If a single string,
1597 plus ``'+'`` and minus ``'-'`` characters are added. Alternatively, set the
1598 labels with :attr:`labels`.
1599
1600 Examples
1601 --------
1602 Set the labels with a single string. Plus ``'+'`` and minus ``'-'``
1603 characters are added automatically.
1604
1605 >>> import pyvista as pv
1606 >>> axes_assembly = pv.AxesAssemblySymmetric()
1607 >>> axes_assembly.y_label = 'Axis'
1608 >>> axes_assembly.y_label
1609 ('+Axis', '-Axis')
1610
1611 Set the labels explicitly with two strings.
1612
1613 >>> axes_assembly.y_label = 'left', 'right'
1614 >>> axes_assembly.y_label
1615 ('left', 'right')
1616
1617 """
1618 return self._get_axis_label(_AxisEnum.y)
1619
1620 @y_label.setter
1621 def y_label(self, label: str | list[str] | tuple[str, str]):
1622 self._set_axis_label(_AxisEnum.y, label)
1623
1624 @property # type: ignore[override]
1625 def z_label(self) -> tuple[str, str]: # numpydoc ignore=RT01
1626 """Return or set the labels for the positive and negative z-axis.
1627
1628 The labels may be set with a single string or two strings. If a single string,
1629 plus ``'+'`` and minus ``'-'`` characters are added. Alternatively, set the
1630 labels with :attr:`labels`.
1631
1632 Examples
1633 --------
1634 Set the labels with a single string. Plus ``'+'`` and minus ``'-'``
1635 characters are added automatically.
1636
1637 >>> import pyvista as pv
1638 >>> axes_assembly = pv.AxesAssemblySymmetric()
1639 >>> axes_assembly.z_label = 'Axis'
1640 >>> axes_assembly.z_label
1641 ('+Axis', '-Axis')
1642
1643 Set the labels explicitly with two strings.
1644
1645 >>> axes_assembly.z_label = 'superior', 'inferior'
1646 >>> axes_assembly.z_label
1647 ('superior', 'inferior')
1648
1649 """
1650 return self._get_axis_label(_AxisEnum.z)
1651
1652 @z_label.setter
1653 def z_label(self, label: str | list[str] | tuple[str, str]):
1654 self._set_axis_label(_AxisEnum.z, label)
1655
1656 def _update_label_positions(self):
1657 # Update plus labels using parent method
1658 AxesAssembly._update_label_positions(self)
1659
1660 # Update minus labels
1661 label_position = self.label_position
1662 label_position_minus = (
1663 -label_position[0],
1664 -label_position[1],
1665 -label_position[2],
1666 )
1667 labels_minus = self._label_actors_symmetric
1668 vector_position_minus = self._get_offset_label_position_vectors(label_position_minus)
1669 for label, position in zip(labels_minus, vector_position_minus, strict=True):
1670 label.relative_position = position
1671
1672
1673 class PlanesAssembly(_XYZAssembly):
1674 """Assembly of orthogonal planes.
1675
1676 Assembly of three orthogonal plane meshes with labels.
1677
1678 The labels can be 2D or 3D, and will follow the camera such that they have the
1679 correct orientation and remain parallel to the edges of the planes.
1680
1681 The positioning of the labels may be customized using the :attr:`label_edge`,
1682 :attr:`label_position`, and :attr:`label_offset` attributes.
1683
1684 .. warning::
1685
1686 The :attr:`camera` must be set before rendering the assembly. Otherwise,
1687 attempting to render it will cause python to crash.
1688
1689 .. versionadded:: 0.45
1690
1691 Parameters
1692 ----------
1693 x_label : str, default: 'YZ'
1694 Text label for the yz-plane. Alternatively, set the label with :attr:`labels`.
1695
1696 y_label : str, default: 'ZX'
1697 Text label for the zx-plane. Alternatively, set the label with :attr:`labels`.
1698
1699 z_label : str, default: 'XY'
1700 Text label for the xy-plane. Alternatively, set the label with :attr:`labels`.
1701
1702 labels : Sequence[str], optional,
1703 Text labels for the planes. This is an alternative parameter to using
1704 :attr:`x_label`, :attr:`y_label`, and :attr:`z_label` separately.
1705
1706 label_color : ColorLike, default: 'black'
1707 Color of the text labels.
1708
1709 show_labels : bool, default: True
1710 Show or hide the text labels.
1711
1712 label_position : float | VectorLike[float], default: 0.5
1713 Normalized relative position of the text labels along each plane's respective
1714 :attr:`label_edge`. The positions are normalized to have a range of
1715 ``[-1.0, 1.0]`` such that ``0.0`` is at the center of the edge and ``-1.0`` and
1716 ``1.0`` are at the corners.
1717
1718 .. note::
1719
1720 The label text is centered horizontally at the specified positions.
1721
1722 label_edge : str, default: 'right'
1723 Edge on which to position each plane's label. Can be ``'top'``, ``'bottom'``,
1724 ``'right'``, or ``'left'``. Use a single value to set the edge for all labels
1725 or set each edge independently.
1726
1727 label_offset : float | VectorLike[float], optional
1728 Vertical offset of the text labels. The offset is proportional to
1729 the :attr:`~pyvista.Prop3D.length` of the assembly. Positive values move the labels away
1730 from the center; negative values move them towards it.
1731
1732 label_size : int, default: 50
1733 Size of the text labels. If :attr:`label_mode` is ``'2D'``, this is the
1734 font size. If :attr:`label_mode` is ``'3D'``, the labels are scaled
1735 proportional to the :attr:`~pyvista.Prop3D.length` of the assembly.
1736
1737 label_mode : '2D' | '3D', default: '2D'
1738 Mode to use for text labels. In 2D mode, the label actors are always visible
1739 and have a constant size regardless of window size. In 3D mode, the label actors
1740 may be occluded by other geometry and will scale with changes to the window
1741 size. The two modes also have minor differences in appearance and behavior in
1742 terms of how they follow the camera.
1743
1744 x_color : ColorLike, optional
1745 Color of the xy-plane.
1746
1747 y_color : ColorLike, optional
1748 Color of the yz-plane.
1749
1750 z_color : ColorLike, optional
1751 Color of the zx-plane.
1752
1753 opacity : float, default: 0.3
1754 Opacity of the planes.
1755
1756 position : VectorLike[float], default: (0.0, 0.0, 0.0)
1757 Position of the planes in space.
1758
1759 orientation : VectorLike[float], default: (0, 0, 0)
1760 Orientation angles of the assembly which define rotations about the
1761 world's x-y-z axes. The angles are specified in degrees and in
1762 x-y-z order. However, the actual rotations are applied in the
1763 around the y-axis first, then the x-axis, and finally the z-axis.
1764
1765 origin : VectorLike[float], default: (0.0, 0.0, 0.0)
1766 Origin of the assembly. This is the point about which all rotations take place.
1767 The rotations are defined by the :attr:`~pyvista.Prop3D.orientation`.
1768
1769 scale : VectorLike[float], default: (1.0, 1.0, 1.0)
1770 Scaling factor applied to the assembly.
1771
1772 user_matrix : MatrixLike[float], optional
1773 A 4x4 transformation matrix applied to the assembly. Defaults to the identity
1774 matrix. The user matrix is the last transformation applied to the actor.
1775
1776 name : str, optional
1777 The name of this assembly used when tracking on a plotter.
1778
1779 .. versionadded:: 0.45
1780
1781 **kwargs
1782 Keyword arguments passed to :class:`pyvista.OrthogonalPlanesSource`.
1783
1784 Examples
1785 --------
1786 Fit planes to a model of a human.
1787
1788 >>> import numpy as np
1789 >>> import pyvista as pv
1790 >>> from pyvista import examples
1791 >>> human = examples.download_human()
1792 >>> labels = 'Sagittal', 'Coronal', 'Transverse'
1793 >>> planes = pv.PlanesAssembly(
1794 ... bounds=human.bounds, labels=labels, label_size=25
1795 ... )
1796
1797 Plot the planes and the model.
1798
1799 >>> pl = pv.Plotter()
1800 >>> human_actor = pl.add_mesh(human, scalars='Color', rgb=True)
1801 >>> _ = pl.add_actor(planes)
1802 >>> planes.camera = pl.camera
1803 >>> pl.show()
1804
1805 Apply a transformation to the planes and the model.
1806
1807 >>> transform = np.array(
1808 ... [
1809 ... [0.70645893, 0.69636424, 0.12646197, 1.0],
1810 ... [-0.62246712, 0.69636424, -0.35722756, 2.0],
1811 ... [-0.33682409, 0.17364818, 0.92541658, 3.0],
1812 ... [0.0, 0.0, 0.0, 1.0],
1813 ... ]
1814 ... )
1815 >>> planes.user_matrix = transform
1816 >>> human_actor.user_matrix = transform
1817
1818 >>> pl = pv.Plotter()
1819 >>> _ = pl.add_actor(human_actor)
1820 >>> _ = pl.add_actor(planes)
1821 >>> planes.camera = pl.camera
1822 >>> pl.show()
1823
1824 Create a new assembly and customize the colors and opacity.
1825
1826 >>> color = pv.global_theme.color
1827 >>> planes = pv.PlanesAssembly(
1828 ... bounds=human.bounds,
1829 ... x_color=color,
1830 ... y_color=color,
1831 ... z_color=color,
1832 ... opacity=1.0,
1833 ... )
1834
1835 Since the planes are opaque, the 3D labels may be occluded. Use 2D labels instead
1836 so the labels are always visible.
1837
1838 >>> planes.label_mode = '2D'
1839
1840 Offset the labels to position them inside the bounds of the planes.
1841
1842 >>> planes.label_offset = -0.05
1843
1844 Move the labels for the two larger planes closer to the corners.
1845
1846 >>> planes.label_position = (0.8, 0.8, 0.5)
1847
1848 Visualize the result.
1849
1850 >>> pl = pv.Plotter()
1851 >>> _ = pl.add_mesh(human, scalars='Color', rgb=True)
1852 >>> _ = pl.add_actor(planes)
1853 >>> planes.camera = pl.camera
1854 >>> pl.show()
1855
1856 """
1857
1858 DEFAULT_LABELS = _XYZTuple('YZ', 'ZX', 'XY')
1859
1860 def __init__(
1861 self,
1862 *,
1863 x_label: str | None = None,
1864 y_label: str | None = None,
1865 z_label: str | None = None,
1866 labels: Sequence[str] | None = None,
1867 label_color: ColorLike = 'black',
1868 show_labels: bool = True,
1869 label_position: float | VectorLike[float] = 0.5,
1870 label_edge: Literal['top', 'bottom', 'right', 'left'] | Sequence[str] = 'right',
1871 label_offset: float = 0.05,
1872 label_size: int = 50,
1873 label_mode: Literal['2D', '3D'] = '3D',
1874 x_color: ColorLike | None = None,
1875 y_color: ColorLike | None = None,
1876 z_color: ColorLike | None = None,
1877 opacity: float | VectorLike[float] = 0.3,
1878 position: VectorLike[float] = (0.0, 0.0, 0.0),
1879 orientation: VectorLike[float] = (0.0, 0.0, 0.0),
1880 origin: VectorLike[float] = (0.0, 0.0, 0.0),
1881 scale: float | VectorLike[float] = (1.0, 1.0, 1.0),
1882 user_matrix: MatrixLike[float] | None = None,
1883 name: str | None = None,
1884 **kwargs: Unpack[_OrthogonalPlanesKwargs],
1885 ):
1886 self._camera = None
1887
1888 # Init plane actors
1889 self._plane_actors = (Actor(), Actor(), Actor())
1890 # Init planes from source
1891 self._geometry_source = OrthogonalPlanesSource(**kwargs)
1892 self._planes = self._geometry_source.output
1893 self._plane_sources = self._geometry_source.sources
1894
1895 for actor, dataset in zip(self._plane_actors, self.planes, strict=True):
1896 actor.mapper = pv.DataSetMapper(dataset=dataset)
1897
1898 # Init label actors
1899 self._axis_actors = (_AxisActor(), _AxisActor(), _AxisActor())
1900
1901 # Tempt init values for call to super class, will validate inputs later
1902 self._label_offset = 0.05
1903 self._label_edge = ('right', 'right', 'right')
1904 self._label_position = 0.5, 0.5, 0.5
1905
1906 _XYZAssembly.__init__(
1907 self,
1908 xyz_actors=self._plane_actors,
1909 xyz_label_actors=self._axis_actors,
1910 x_label=x_label,
1911 y_label=y_label,
1912 z_label=z_label,
1913 labels=labels,
1914 label_color=label_color,
1915 show_labels=show_labels,
1916 label_position=label_position,
1917 label_size=label_size,
1918 x_color=x_color,
1919 y_color=y_color,
1920 z_color=z_color,
1921 position=position,
1922 orientation=orientation,
1923 origin=origin,
1924 scale=scale,
1925 user_matrix=user_matrix,
1926 name=name,
1927 )
1928
1929 self.opacity = opacity # type: ignore[assignment]
1930 self.label_mode = label_mode
1931 self.label_offset = label_offset
1932 self.label_edge = label_edge
1933
1934 # Set default properties
1935 for actor in self._plane_actors:
1936 prop = actor.prop
1937 prop.show_edges = True
1938 prop.line_width = 3
1939
1940 # Set default text properties
1941 # TODO: implement set_text_prop() and use that instead
1942 for label in self._label_actor_iterator:
1943 prop = label.prop
1944 prop.justification_vertical = 'center'
1945 prop.justification_horizontal = 'center'
1946
1947 def __repr__(self):
1948 """Representation of the planes assembly."""
1949 mat_info = 'Identity' if np.array_equal(self.user_matrix, np.eye(4)) else 'Set'
1950 bnds = self.bounds
1951
1952 attr = [
1953 f'{type(self).__name__} ({hex(id(self))})',
1954 f' Resolution: {self._geometry_source.resolution}',
1955 f' Normal sign: {self._geometry_source.normal_sign}',
1956 f" X label: '{self.x_label}'",
1957 f" Y label: '{self.y_label}'",
1958 f" Z label: '{self.z_label}'",
1959 f' Label color: {self.label_color}',
1960 f' Show labels: {self.show_labels}',
1961 f' Label position: {self.label_position}',
1962 f' Label edge: {self.label_edge}',
1963 f' Label offset: {self.label_offset}',
1964 f" Label mode: '{self.label_mode}'",
1965 f' X Color: {self.x_color}',
1966 f' Y Color: {self.y_color}',
1967 f' Z Color: {self.z_color}',
1968 f' Position: {self.position}',
1969 f' Orientation: {self.orientation}',
1970 f' Origin: {self.origin}',
1971 f' Scale: {self.scale}',
1972 f' User matrix: {mat_info}',
1973 f' X Bounds {bnds.x_min:.3E}, {bnds.x_max:.3E}',
1974 f' Y Bounds {bnds.y_min:.3E}, {bnds.y_max:.3E}',
1975 f' Z Bounds {bnds.z_min:.3E}, {bnds.z_max:.3E}',
1976 ]
1977 return '\n'.join(attr)
1978
1979 @property
1980 def labels(self) -> tuple[str, str, str]: # numpydoc ignore=RT01
1981 """Return or set the labels for the planes.
1982
1983 This property may be used as an alternative to using :attr:`x_label`,
1984 :attr:`y_label`, and :attr:`z_label` separately.
1985
1986 Examples
1987 --------
1988 >>> import pyvista as pv
1989 >>> planes = pv.PlanesAssembly()
1990 >>> planes.labels = ['Sagittal', 'Coronal', 'Transverse']
1991 >>> planes.labels
1992 ('Sagittal', 'Coronal', 'Transverse')
1993
1994 """
1995 return self.x_label, self.y_label, self.z_label
1996
1997 @labels.setter
1998 def labels(self, labels: list[str] | tuple[str, str, str]):
1999 labels = _validate_label_sequence(labels, n_labels=3, name='labels')
2000 self.x_label = labels[0]
2001 self.y_label = labels[1]
2002 self.z_label = labels[2]
2003
2004 @property
2005 def x_label(self) -> str: # numpydoc ignore=RT01
2006 """Text label for the yz-plane.
2007
2008 Examples
2009 --------
2010 >>> import pyvista as pv
2011 >>> planes = pv.PlanesAssembly()
2012 >>> planes.x_label = 'This plane'
2013 >>> planes.x_label
2014 'This plane'
2015
2016 """
2017 return self._axis_actors[0].GetTitle()
2018
2019 @x_label.setter
2020 def x_label(self, label: str):
2021 self._axis_actors[0].SetTitle(label)
2022 self.planes.set_block_name(0, label)
2023
2024 @property
2025 def y_label(self) -> str: # numpydoc ignore=RT01
2026 """Text label for the zx-plane.
2027
2028 Examples
2029 --------
2030 >>> import pyvista as pv
2031 >>> planes = pv.PlanesAssembly()
2032 >>> planes.y_label = 'This plane'
2033 >>> planes.y_label
2034 'This plane'
2035
2036 """
2037 return self._axis_actors[1].GetTitle()
2038
2039 @y_label.setter
2040 def y_label(self, label: str):
2041 self._axis_actors[1].SetTitle(label)
2042 self.planes.set_block_name(1, label)
2043
2044 @property
2045 def z_label(self) -> str: # numpydoc ignore=RT01
2046 """Text label for the xy-plane.
2047
2048 Examples
2049 --------
2050 >>> import pyvista as pv
2051 >>> planes = pv.PlanesAssembly()
2052 >>> planes.z_label = 'This plane'
2053 >>> planes.z_label
2054 'This plane'
2055
2056 """
2057 return self._axis_actors[2].GetTitle()
2058
2059 @z_label.setter
2060 def z_label(self, label: str):
2061 self._axis_actors[2].SetTitle(label)
2062 self.planes.set_block_name(2, label)
2063
2064 @property
2065 def label_size(self) -> int: # numpydoc ignore=RT01
2066 """Size of the text labels.
2067
2068 Must be a positive integer.
2069 """
2070 return self._label_size
2071
2072 @label_size.setter
2073 def label_size(self, size: int):
2074 valid_size = _validation.validate_number(
2075 size,
2076 must_be_in_range=[0, np.inf],
2077 must_be_integer=True,
2078 dtype_out=int,
2079 name='label size',
2080 )
2081 self._label_size = valid_size
2082 # 2D labels use font size (int) but 3D labels use a scaling factor (float)
2083 # For 3D labels, we re-scale the text proportional to the planes assembly
2084 # Values on the order of 0.01-0.05 seem to work best. Use a normalization
2085 # factor so that input values are on the order of 10-50 and roughly match 2D sizes
2086 NORM_FACTOR = 1000
2087 scale_3d = self.planes.length * float(valid_size) / NORM_FACTOR
2088
2089 # In VTK 9.6+, the 3D label size depends on the 2D label size, so in the 3D case
2090 # we need to reset the 2D font size to match the VTK default value of 12
2091 font_size_2d = (
2092 valid_size if hasattr(self, 'label_mode') and self.label_mode == '2D' else 12
2093 )
2094 for axis in self._axis_actors:
2095 axis.GetTitleActor().SetScale(scale_3d) # 3D labels
2096 axis.GetTitleTextProperty().SetFontSize(font_size_2d) # 2D labels
2097
2098 @property
2099 def label_position(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
2100 """Normalized relative position of the text labels along the edge of each plane.
2101
2102 Labels are positioned relative to each plane's respective :attr:`label_edge`.
2103 The positions are normalized to have a range of ``[-1.0, 1.0]`` such that ``0.0``
2104 is at the center of the edge and ``-1.0`` and ``1.0`` are at the corners.
2105
2106 .. note::
2107
2108 The label text is centered horizontally at the specified positions.
2109
2110 Examples
2111 --------
2112 Position the labels at the center (along the edges) and plot the assembly.
2113
2114 >>> import pyvista as pv
2115 >>> planes = pv.PlanesAssembly(label_position=0)
2116 >>> planes.label_position
2117 (0.0, 0.0, 0.0)
2118
2119 >>> pl = pv.Plotter()
2120 >>> _ = pl.add_actor(planes)
2121 >>> planes.camera = pl.camera
2122 >>> pl.show()
2123
2124 Position the labels at the corners.
2125
2126 >>> planes.label_position = 1.0
2127 >>> pl = pv.Plotter()
2128 >>> _ = pl.add_actor(planes)
2129 >>> planes.camera = pl.camera
2130 >>> pl.show()
2131
2132 Vary the position of the labels independently for each plane. The values may be
2133 negative and/or exceed a value of ``1.0``.
2134
2135 >>> planes.label_position = (-1.3, -1.0, -0.5)
2136 >>> pl = pv.Plotter()
2137 >>> _ = pl.add_actor(planes)
2138 >>> planes.camera = pl.camera
2139 >>> pl.show()
2140
2141 """
2142 return self._label_position
2143
2144 @label_position.setter
2145 def label_position(self, position: int | VectorLike[int]):
2146 self._label_position = _validation.validate_array3(
2147 position,
2148 broadcast=True,
2149 name='Label position',
2150 dtype_out=float,
2151 to_tuple=True,
2152 )
2153 self._update_label_positions()
2154
2155 @property
2156 def label_edge(self) -> tuple[str, str, str]: # numpydoc ignore=RT01
2157 """Edge on which to position each plane's label.
2158
2159 Edge can be ``'top'``,``'bottom'``,``'right'``, or ``'left'``, and can be
2160 set independently for each plane or to the same edge for all planes.
2161
2162 The edge is relative to each plane's local ``i`` and ``j`` coordinates.
2163
2164 Examples
2165 --------
2166 Position the labels at the top edge and plot.
2167
2168 >>> import pyvista as pv
2169 >>> planes = pv.PlanesAssembly(label_edge='top')
2170 >>> planes.label_edge
2171 ('top', 'top', 'top')
2172
2173 >>> pl = pv.Plotter()
2174 >>> _ = pl.add_actor(planes)
2175 >>> planes.camera = pl.camera
2176 >>> pl.show()
2177
2178 Position the labels at the bottom.
2179
2180 >>> planes.label_edge = 'bottom'
2181 >>> pl = pv.Plotter()
2182 >>> _ = pl.add_actor(planes)
2183 >>> planes.camera = pl.camera
2184 >>> pl.show()
2185
2186 Vary the edge of the labels independently for each plane.
2187
2188 >>> planes.label_edge = ('top', 'right', 'left')
2189 >>> pl = pv.Plotter()
2190 >>> _ = pl.add_actor(planes)
2191 >>> planes.camera = pl.camera
2192 >>> pl.show()
2193
2194 """
2195 return self._label_edge
2196
2197 @label_edge.setter
2198 def label_edge(self, edge: Literal['top', 'bottom', 'right', 'left'] | Sequence[str]):
2199 valid_edge = (
2200 [edge] * 3
2201 if isinstance(edge, str)
2202 else _validate_label_sequence(edge, n_labels=3, name='label edge')
2203 )
2204 for edge_ in valid_edge:
2205 _validation.check_contains(
2206 ['top', 'bottom', 'right', 'left'],
2207 must_contain=edge_,
2208 name='label_edge',
2209 )
2210 self._label_edge = tuple(valid_edge)
2211 self._update_label_positions()
2212
2213 @property
2214 def label_offset(self) -> float: # numpydoc ignore=RT01
2215 """Vertical offset of the text labels.
2216
2217 The offset is proportional to the :attr:`~pyvista.Prop3D.length` of the assembly. Positive
2218 values move the labels away from the center; negative values move them
2219 towards it.
2220 """
2221 return self._label_offset
2222
2223 @label_offset.setter
2224 def label_offset(self, offset: float):
2225 self._label_offset = _validation.validate_number(offset, dtype_out=float)
2226 self._update_label_positions()
2227
2228 @property
2229 def label_mode(self) -> Literal['2D', '3D']: # numpydoc ignore=RT01
2230 """Mode to use for text labels.
2231
2232 Mode must be either ``'2D'`` or ``'3D'``. In 2D mode, the label actors are
2233 always visible and have a constant size regardless of window size. In 3D mode,
2234 the label actors may be occluded by other geometry and will scale with changes
2235 to the window size. The two modes also have minor differences in appearance as
2236 well as behavior in terms of how they follow the camera.
2237 """
2238 return self._label_mode
2239
2240 @label_mode.setter
2241 def label_mode(self, mode: Literal['2D', '3D']):
2242 _validation.check_contains(['2D', '3D'], must_contain=mode, name='label_mode')
2243 self._label_mode = mode
2244 use_2D = mode == '2D'
2245 for axis in self._axis_actors:
2246 axis.SetUse2DMode(use_2D)
2247
2248 # The 3D label size depends on the 2D label size so we need to reset this property
2249 self.label_size = self.label_size
2250
2251 @property
2252 def x_color(self) -> Color: # numpydoc ignore=RT01
2253 """Color of the yz-plane."""
2254 return self._plane_actors[0].prop.color
2255
2256 @x_color.setter
2257 def x_color(self, color: ColorLike):
2258 self._plane_actors[0].prop.color = color
2259
2260 @property
2261 def y_color(self) -> Color: # numpydoc ignore=RT01
2262 """Color of the zx-plane."""
2263 return self._plane_actors[1].prop.color
2264
2265 @y_color.setter
2266 def y_color(self, color: ColorLike):
2267 self._plane_actors[1].prop.color = color
2268
2269 @property
2270 def z_color(self) -> Color: # numpydoc ignore=RT01
2271 """Color of the xy-plane."""
2272 return self._plane_actors[2].prop.color
2273
2274 @z_color.setter
2275 def z_color(self, color: ColorLike):
2276 self._plane_actors[2].prop.color = color
2277
2278 @property
2279 def opacity(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
2280 """Opacity of the planes."""
2281 return self._opacity
2282
2283 @opacity.setter
2284 def opacity(self, opacity: float):
2285 valid_opacity = _validation.validate_array3(
2286 opacity, broadcast=True, dtype_out=float, to_tuple=True
2287 )
2288 self._opacity = valid_opacity
2289 for actor, opacity_ in zip(self._plane_actors, valid_opacity, strict=True):
2290 actor.prop.opacity = opacity_
2291
2292 @property
2293 def camera(self): # numpydoc ignore=RT01
2294 """Camera to use for displaying the labels."""
2295 return self._camera
2296
2297 @camera.setter
2298 def camera(self, camera):
2299 self._camera = camera
2300 for axis in self._axis_actors:
2301 axis.SetCamera(camera)
2302
2303 @property
2304 def planes(self):
2305 """Get the orthogonal plane datasets of the assembly.
2306
2307 The planes are :class:`pyvista.PolyData` meshes stored as a
2308 :class:`pyvista.MultiBlock`. The names of the blocks match the names of the
2309 assembly's :attr:`labels`.
2310
2311 The planes are initially generated with :class:`pyvista.OrthogonalPlanesSource`.
2312
2313 Returns
2314 -------
2315 pyvista.MultiBlock
2316 Composite mesh with three planes.
2317
2318 """
2319 return self._planes
2320
2321 def _update_label_positions(self):
2322 axis_actors = self._axis_actors
2323 plane_sources = self._plane_sources
2324 transformation_matrix = self._transformation_matrix
2325
2326 def transform_point(point):
2327 return (transformation_matrix @ (*point, 1))[:3]
2328
2329 def set_axis_location(plane_id, edge: str, position: float):
2330 this_plane_source = plane_sources[plane_id]
2331 this_axis_actor = axis_actors[plane_id]
2332
2333 # Get vectors which define the plane
2334 origin, point1, point2 = (
2335 np.array(this_plane_source.GetOrigin()),
2336 np.array(this_plane_source.GetPoint1()),
2337 np.array(this_plane_source.GetPoint2()),
2338 )
2339
2340 vector1 = point1 - origin
2341 vector2 = point2 - origin
2342
2343 # Define corners
2344 corner_bottom_left = origin
2345 corner_bottom_right = origin + vector1
2346 corner_top_left = origin + vector2
2347 corner_top_right = corner_bottom_right + vector2
2348
2349 # Define axis points in counter-clockwise order
2350 if edge == 'top':
2351 axis_point1, axis_point2 = corner_top_right, corner_top_left
2352 elif edge == 'left':
2353 axis_point1, axis_point2 = corner_top_left, corner_bottom_left
2354 elif edge == 'bottom':
2355 axis_point1, axis_point2 = corner_bottom_left, corner_bottom_right
2356 else: # 'right'
2357 axis_point1, axis_point2 = corner_bottom_right, corner_top_right
2358
2359 # Move axis to position along the edge
2360 axis_vector = axis_point1 - axis_point2
2361 # Define position relative to center of edge
2362 position_vector = np.abs(axis_vector) * position * 0.5
2363 axis_point1 += position_vector
2364 axis_point2 += position_vector
2365
2366 # Add offset
2367 axis_dir = axis_vector / np.linalg.norm(axis_vector)
2368 offset_dir = np.cross(axis_dir, this_plane_source.GetNormal())
2369 offset_dir = -1 * offset_dir / np.linalg.norm(offset_dir)
2370 offset_mag = self.planes.length * self.label_offset
2371 offset = offset_mag * offset_dir
2372 axis_point1 += offset
2373 axis_point2 += offset
2374
2375 # Set axis points
2376 this_axis_actor.SetPoint1(transform_point(axis_point1))
2377 this_axis_actor.SetPoint2(transform_point(axis_point2))
2378
2379 edge = self.label_edge
2380 position = self.label_position
2381 set_axis_location(0, edge[0], position[0])
2382 set_axis_location(1, edge[1], position[1])
2383 set_axis_location(2, edge[2], position[2])
2384
2385 def _post_set_update(self):
2386 _XYZAssembly._post_set_update(self)
2387 # Need to manually update axis actors
2388 self._update_label_positions()
2389
2390
2391 class _AxisActor(DisableVtkSnakeCase, _vtk.vtkAxisActor):
2392 def __init__(self):
2393 super().__init__()
2394 # Only show the title
2395 self.TitleVisibilityOn()
2396 self.MinorTicksVisibleOff()
2397 self.TickVisibilityOff()
2398 self.DrawGridlinesOff()
2399 self.AxisVisibilityOff() # Turn this on for debugging
2400
2401 # Set empty tick labels
2402 labels = _vtk.vtkStringArray()
2403 labels.SetNumberOfTuples(0)
2404 # labels.SetValue(0, "")
2405 self.SetLabels(labels)
2406
2407 # Ignore the axis bounds when rendering. Otherwise, the bounds must be
2408 # set with SetBounds() every time the axis is updated
2409 self.SetUseBounds(False)
2410
2411 # Format title positioning
2412 offset = (0,) if pv.vtk_version_info < (9, 3) else (0, 0)
2413 self.SetTitleOffset(*offset)
2414 self.SetLabelOffset(0)
2415
2416 # For 2D mode only
2417 self.SetVerticalOffsetXTitle2D(0)
2418 self.SetHorizontalOffsetYTitle2D(0)
2419 text_prop = TextProperty()
2420 text_prop.justification_vertical = 'center'
2421 self.SetTitleTextProperty(text_prop)
2422 self.GetTitleActor()
2423
2424 # For 3D mode only
2425 self.GetProperty().SetLighting(False)
2426
2427 @property
2428 def prop(self) -> TextProperty:
2429 return self.GetTitleTextProperty()