Debian Codegraph @

pyvista/plotting/renderer.py

raw
1 """Module containing pyvista implementation of :vtk:`vtkRenderer`."""
2
3 from __future__ import annotations
4
5 from collections.abc import Iterable
6 from collections.abc import Sequence
7 import contextlib
8 from functools import partial
9 from functools import wraps
10 from html import escape
11 from typing import TYPE_CHECKING
12 from typing import Any
13 from typing import ClassVar
14 from typing import cast
15
16 import numpy as np
17
18 import pyvista as pv
19 from pyvista import MAX_N_COLOR_BARS
20 from pyvista import _vtk
21 from pyvista import vtk_version_info
22 from pyvista._deprecate_positional_args import _deprecate_positional_args
23 from pyvista._warn_external import warn_external
24 from pyvista.core import _validation
25 from pyvista.core._typing_core import BoundsTuple
26 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
27 from pyvista.core.errors import PyVistaDeprecationWarning
28 from pyvista.core.formatting_html import _copy_btn
29 from pyvista.core.formatting_html import _load_css
30 from pyvista.core.formatting_html import _metadata_html
31 from pyvista.core.utilities.helpers import wrap
32 from pyvista.core.utilities.misc import _BoundsSizeMixin
33 from pyvista.core.utilities.misc import _NoNewAttrMixin
34 from pyvista.core.utilities.misc import assert_empty_kwargs
35 from pyvista.core.utilities.misc import try_callback
36
37 from .actor import Actor
38 from .camera import Camera
39 from .charts import Charts
40 from .colors import Color
41 from .colors import get_cycler
42 from .errors import InvalidCameraError
43 from .helpers import view_vectors
44 from .mapper import DataSetMapper
45 from .prop_collection import _PropCollection
46 from .render_passes import RenderPasses
47 from .tools import create_axes_marker
48 from .tools import create_axes_orientation_box
49 from .tools import create_north_arrow
50 from .tools import parse_font_family
51 from .utilities.gl_checks import check_depth_peeling
52 from .utilities.gl_checks import uses_egl
53
54 if TYPE_CHECKING:
55 from pyvista.core._typing_core import RotationLike
56 from pyvista.core.pointset import PolyData
57
58 from .cube_axes_actor import CubeAxesActor
59 from .lights import Light
60
61 ACTOR_LOC_MAP = [
62 'upper right',
63 'upper left',
64 'lower left',
65 'lower right',
66 'center left',
67 'center right',
68 'lower center',
69 'upper center',
70 'center',
71 ]
72
73
74 def map_loc_to_pos(loc, size, border=0.05):
75 """Map location and size to a VTK position and position2.
76
77 Parameters
78 ----------
79 loc : str
80 Location of the actor. Can be a string with values such as 'right',
81 'left', 'upper', or 'lower'.
82 size : Sequence of length 2
83 Size of the actor. It must be a list of length 2.
84 border : float, default: 0.05
85 Size of the border around the actor.
86
87 Returns
88 -------
89 tuple
90 The VTK position and position2 coordinates. Tuple of the form (x, y, size).
91
92 Raises
93 ------
94 ValueError
95 If the ``size`` parameter is not a list of length 2.
96
97 """
98 if not isinstance(size, Sequence) or len(size) != 2:
99 msg = f'`size` must be a list of length 2. Passed value is {size}'
100 raise ValueError(msg)
101
102 if 'right' in loc:
103 x = 1 - size[1] - border
104 elif 'left' in loc:
105 x = border
106 else:
107 x = 0.5 - size[1] / 2
108
109 if 'upper' in loc:
110 y = 1 - size[1] - border
111 elif 'lower' in loc:
112 y = border
113 else:
114 y = 0.5 - size[1] / 2
115
116 return x, y, size
117
118
119 def make_legend_face(face) -> PolyData:
120 """Create the legend face based on the given face.
121
122 Parameters
123 ----------
124 face : str | pyvista.PolyData | NoneType
125 The shape of the legend face. Valid strings are:
126 '-', 'line', '^', 'triangle', 'o', 'circle', 'r', 'rectangle', 'none'.
127 Also accepts ``None`` or instances of ``pyvista.PolyData``.
128
129 Returns
130 -------
131 pyvista.PolyData
132 The legend face as a PolyData object.
133
134 Raises
135 ------
136 ValueError
137 If the provided face value is invalid.
138
139 """
140
141 def normalize(poly):
142 norm_poly = poly.copy() # Avoid mutating input
143 norm_poly.clear_data()
144
145 # Center data
146 norm_poly.points -= np.array(norm_poly.center)
147
148 # Scale so max bounds are [-0.5, 0.5] along x and y axes
149 size = np.array(norm_poly.bounds_size)
150 size[size < 1e-8] = 1 # Avoid division by zero
151 max_xy_size = max(size[0:2])
152 norm_poly.scale(1 / max_xy_size, inplace=True)
153
154 # Add final offset to align the symbol with the adjacent text
155 y_offset = 0.6 # determined experimentally
156 norm_poly.points += (0, y_offset, 0)
157 return norm_poly
158
159 if face is None or face == 'none':
160 legendface = pv.PolyData([0.0, 0.0, 0.0], faces=np.empty(0, dtype=int)) # type: ignore[arg-type]
161 elif face in ['-', 'line']:
162 legendface = pv.Rectangle().scale((1, 0.2, 1))
163 elif face in ['^', 'triangle']:
164 legendface = pv.Triangle()
165 elif face in ['o', 'circle']:
166 legendface = pv.Circle()
167 elif face in ['r', 'rectangle']:
168 legendface = pv.Rectangle()
169 elif isinstance(face, pv.PolyData):
170 legendface = face
171 else:
172 msg = (
173 f'Invalid face "{face}". Must be one of the following:\n'
174 '\t"triangle"\n'
175 '\t"circle"\n'
176 '\t"rectangle"\n'
177 '\t"none"\n'
178 '\tpyvista.PolyData'
179 )
180 raise ValueError(msg)
181
182 # Normalize the geometry
183 legendface = normalize(legendface)
184
185 # Add points to each corner of the normalized geom to define the full extent of the geometry.
186 # This is needed for asymmetric shapes (like a line) because otherwise the legend actor
187 # will do its own scaling and skew the shape
188 rect = normalize(pv.Rectangle())
189 legendface.points = np.append(legendface.points, rect.points, axis=0)
190 return legendface
191
192
193 @_deprecate_positional_args(allowed=['camera', 'point'])
194 def scale_point(camera, point, invert=False): # noqa: FBT002
195 """Scale a point using the camera's transform matrix.
196
197 Parameters
198 ----------
199 camera : Camera
200 The camera who's matrix to use.
201
202 point : sequence[float]
203 Scale point coordinates.
204
205 invert : bool, default: False
206 If ``True``, invert the matrix to transform the point out of
207 the camera's transformed space. Default is ``False`` to
208 transform a point from world coordinates to the camera's
209 transformed space.
210
211 Returns
212 -------
213 tuple
214 Scaling of the camera in ``(x, y, z)``.
215
216 """
217 if invert:
218 mtx = _vtk.vtkMatrix4x4()
219 mtx.DeepCopy(camera.GetModelTransformMatrix())
220 mtx.Invert()
221 else:
222 mtx = camera.GetModelTransformMatrix()
223 scaled = mtx.MultiplyDoublePoint((point[0], point[1], point[2], 0.0))
224 return (scaled[0], scaled[1], scaled[2])
225
226
227 class CameraPosition(_NoNewAttrMixin):
228 """Container to hold camera location attributes.
229
230 Parameters
231 ----------
232 position : sequence[float]
233 Position of the camera.
234
235 focal_point : sequence[float]
236 The focal point of the camera.
237
238 viewup : sequence[float]
239 View up of the camera.
240
241 """
242
243 def __init__(self, position, focal_point, viewup) -> None:
244 """Initialize a new camera position descriptor."""
245 self._position = position
246 self._focal_point = focal_point
247 self._viewup = viewup
248
249 def to_list(self):
250 """Convert to a list of the position, focal point, and viewup.
251
252 Returns
253 -------
254 list
255 List of the position, focal point, and view up of the camera.
256
257 Examples
258 --------
259 >>> import pyvista as pv
260 >>> pl = pv.Plotter()
261 >>> pl.camera_position.to_list()
262 [(0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
263
264 """
265 return [self._position, self._focal_point, self._viewup]
266
267 def __str__(self) -> str:
268 """List representation method."""
269 return '[{},\n {},\n {}]'.format(*self.to_list())
270
271 def __repr__(self) -> str:
272 """Explicit representation of CameraPosition."""
273 return (
274 f'{CameraPosition.__name__}(position={self._position},\n'
275 f' focal_point={self._focal_point},\n'
276 f' viewup={self._viewup})'
277 )
278
279 def _repr_html_(self) -> str:
280 """Return an HTML representation for Jupyter notebooks."""
281
282 def _fmt_vec(vec: tuple[float, ...]) -> str:
283 return '(' + ', '.join(f'{v:.4f}' for v in vec) + ')'
284
285 pos = _fmt_vec(self._position)
286 foc = _fmt_vec(self._focal_point)
287 vup = _fmt_vec(self._viewup)
288
289 css = _load_css()
290 copy_all = _copy_btn(repr(self.to_list()))
291 meta = _metadata_html(
292 [
293 ('position', [('', pos)], pos),
294 ('focal_point', [('', foc)], foc),
295 ('viewup', [('', vup)], vup),
296 ]
297 )
298 text_fallback = escape(repr(self))
299
300 return (
301 f'<div><style>{css}</style>'
302 f"<pre class='pv-text-repr-fallback'>{text_fallback}</pre>"
303 "<div class='pv-wrap' style='display:none'>"
304 "<div class='pv-header'>"
305 "<div class='pv-header-text'>"
306 f"<div class='pv-obj-type'>CameraPosition{copy_all}</div>"
307 '</div></div>'
308 f'{meta}'
309 '</div></div>'
310 )
311
312 def __getitem__(self, index):
313 """Fetch a component by index location like a list."""
314 return self.to_list()[index]
315
316 def __eq__(self, other):
317 """Comparison operator to act on list version of CameraPosition object."""
318 if isinstance(other, CameraPosition):
319 return self.to_list() == other.to_list()
320 return self.to_list() == other
321
322 __hash__ = None # type: ignore[assignment] # https://github.com/pyvista/pyvista/pull/7671
323
324 @property
325 def position(self): # numpydoc ignore=RT01
326 """Location of the camera in world coordinates."""
327 return self._position
328
329 @position.setter
330 def position(self, value) -> None:
331 self._position = value
332
333 @property
334 def focal_point(self): # numpydoc ignore=RT01
335 """Location of the camera's focus in world coordinates."""
336 return self._focal_point
337
338 @focal_point.setter
339 def focal_point(self, value) -> None:
340 self._focal_point = value
341
342 @property
343 def viewup(self): # numpydoc ignore=RT01
344 """Viewup vector of the camera."""
345 return self._viewup
346
347 @viewup.setter
348 def viewup(self, value) -> None:
349 self._viewup = value
350
351
352 class Renderer(_NoNewAttrMixin, _BoundsSizeMixin, DisableVtkSnakeCase, _vtk.vtkOpenGLRenderer):
353 """Renderer class."""
354
355 # map camera_position string to an attribute
356 CAMERA_STR_ATTR_MAP: ClassVar[dict[str, str]] = {
357 'xy': 'view_xy',
358 'xz': 'view_xz',
359 'yz': 'view_yz',
360 'yx': 'view_yx',
361 'zx': 'view_zx',
362 'zy': 'view_zy',
363 'iso': 'view_isometric',
364 }
365
366 @_deprecate_positional_args(allowed=['parent'])
367 def __init__( # noqa: PLR0917
368 self,
369 parent,
370 border=True, # noqa: FBT002
371 border_color='w',
372 border_width=2.0,
373 ) -> None: # numpydoc ignore=PR01,RT01
374 """Initialize the renderer."""
375 super().__init__()
376 self._actors = _PropCollection(self.GetViewProps())
377 self.parent = parent # weakref.proxy to the plotter from Renderers
378 self._theme = parent.theme
379 self.bounding_box_actor: Actor | None = None
380 self.axes_actor: _vtk.vtkAxesActor | None = None
381 self.axes_widget: _vtk.vtkOrientationMarkerWidget | None = None
382 self.scale = [1.0, 1.0, 1.0]
383 self.AutomaticLightCreationOff()
384 self._labels: dict[
385 str, tuple[_vtk.vtkPolyData | _vtk.vtkImageData, str, Color]
386 ] = {} # tracks labeled actors
387 self._legend: _vtk.vtkLegendBoxActor | None = None
388 self._floor: PolyData | None = None
389 self._floors: list[Actor] = []
390 self._floor_kwargs: list[dict[str, Any]] = []
391 # this keeps track of lights added manually to prevent garbage collection
392 self._lights: list[Light] = []
393 self._camera: Camera | None = Camera(self)
394 self.SetActiveCamera(self._camera)
395 self._empty_str: _vtk.vtkStringArray | None = (
396 None # used to track reference to a vtkStringArray
397 )
398 self._shadow_pass = None
399 self._render_passes = RenderPasses(self)
400 self.cube_axes_actor: CubeAxesActor | None = None
401
402 # This is a private variable to keep track of how many colorbars exist
403 # This allows us to keep adding colorbars without overlapping
404 self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
405 self._scalar_bar_slot_lookup: dict[str, int] = {}
406 self._charts: Charts | None = None
407
408 self._border_actor: _vtk.vtkActor2D | None = None
409 if border:
410 self.add_border(border_color, border_width)
411
412 self.set_color_cycler(self._theme.color_cycler)
413 self._closed = False
414 self._bounding_box: _vtk.vtkOutlineCornerSource | _vtk.vtkCubeSource | None = None
415 self._box_object: PolyData | None = None
416 self._marker_actor: _vtk.vtkAxesActor | None = None
417
418 @property
419 def camera_set(self) -> bool: # numpydoc ignore=RT01
420 """Get or set whether this camera has been configured."""
421 if self.camera is None: # pragma: no cover
422 return False
423 return self.camera.is_set
424
425 @camera_set.setter
426 def camera_set(self, is_set: bool) -> None:
427 self.camera.is_set = is_set
428
429 def set_color_cycler(self, color_cycler) -> None:
430 """Set or reset this renderer's color cycler.
431
432 This color cycler is iterated over by each sequential :meth:`~pyvista.Plotter.add_mesh`
433 call to set the default color of the dataset being plotted.
434
435 When setting, the value must be either a list of color-like objects,
436 or a cycler of color-like objects. If the value passed is a single
437 string, it must be one of:
438
439 * ``'default'`` - Use the default color cycler (matches matplotlib's default)
440 * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
441 * ``'all'`` - Cycle through all of the available colors in
442 ``pyvista.plotting.colors.hexcolors``
443
444 Setting to ``None`` will disable the use of the color cycler on this
445 renderer.
446
447 .. note::
448 If a mesh has scalar data, set ``color=True`` in the call to
449 :meth:`~pyvista.Plotter.add_mesh` to color the mesh with the
450 next color in the cycler. Otherwise, the mesh's scalars are used
451 to color the mesh by default.
452
453 Parameters
454 ----------
455 color_cycler : str | cycler.Cycler | sequence[ColorLike]
456 The colors to cycle through.
457
458 Examples
459 --------
460 Set the default color cycler to iterate through red, green, and blue.
461
462 >>> import pyvista as pv
463 >>> pl = pv.Plotter()
464 >>> pl.renderer.set_color_cycler(['red', 'green', 'blue'])
465 >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0))) # red
466 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0))) # green
467 >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0))) # blue
468 >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0))) # red again
469 >>> pl.show()
470
471 Load a mesh with active scalars and split it into two separate meshes.
472
473 >>> mesh = pv.Wavelet()
474 >>> mesh.active_scalars_name
475 'RTData'
476
477 >>> a = mesh.clip(invert=True)
478 >>> b = mesh.clip(invert=False)
479
480 Enable color cycling and set ``color=True`` to force the meshes to be colored with the
481 cycler's colors.
482
483 >>> pv.global_theme.color_cycler = 'default'
484 >>> pl = pv.Plotter()
485 >>> _ = pl.add_mesh(a, color=True)
486 >>> _ = pl.add_mesh(b, color=True)
487 >>> pl.show()
488
489 """
490 cycler = get_cycler(color_cycler)
491 if cycler is not None:
492 # Color cycler - call object to generate `cycle` instance
493 self._color_cycle = cycler()
494 else:
495 self._color_cycle = None
496
497 @property
498 def next_color(self): # numpydoc ignore=RT01
499 """Return next color from this renderer's color cycler."""
500 if self._color_cycle is None:
501 return self._theme.color
502 return next(self._color_cycle)['color']
503
504 @property
505 def camera_position(self): # numpydoc ignore=RT01
506 """Return or set the camera position of active render window.
507
508 Returns
509 -------
510 pyvista.CameraPosition
511 Camera position.
512
513 """
514 return CameraPosition(
515 scale_point(self.camera, self.camera.position, invert=True),
516 scale_point(self.camera, self.camera.focal_point, invert=True),
517 self.camera.up,
518 )
519
520 @camera_position.setter
521 def camera_position(self, camera_location):
522 if camera_location is None:
523 return
524 elif isinstance(camera_location, str):
525 camera_location = camera_location.lower()
526 if camera_location not in self.CAMERA_STR_ATTR_MAP:
527 msg = (
528 'Invalid view direction. '
529 'Use one of the following:\n '
530 f'{", ".join(self.CAMERA_STR_ATTR_MAP)}'
531 )
532 raise InvalidCameraError(msg)
533
534 getattr(self, self.CAMERA_STR_ATTR_MAP[camera_location])()
535
536 elif isinstance(camera_location[0], (int, float)):
537 if len(camera_location) != 3:
538 raise InvalidCameraError
539 self.view_vector(camera_location)
540 else:
541 # check if a valid camera position
542 if not isinstance(camera_location, CameraPosition) and (
543 not len(camera_location) == 3 or any(len(item) != 3 for item in camera_location)
544 ):
545 raise InvalidCameraError
546
547 # everything is set explicitly
548 self.camera.position = scale_point(self.camera, camera_location[0], invert=False)
549 self.camera.focal_point = scale_point(self.camera, camera_location[1], invert=False)
550 self.camera.up = camera_location[2]
551
552 # reset clipping range
553 self.reset_camera_clipping_range()
554 self.camera_set = True
555 self.Modified()
556
557 def reset_camera_clipping_range(self) -> None:
558 """Reset the camera clipping range based on the bounds of the visible actors.
559
560 This ensures that no props are cut off
561 """
562 self.ResetCameraClippingRange()
563
564 @property
565 def camera(self): # numpydoc ignore=RT01
566 """Return the active camera for the rendering scene."""
567 return self._camera
568
569 @camera.setter
570 def camera(self, source) -> None:
571 self._camera = source
572 self.SetActiveCamera(self._camera)
573 self.camera_position = CameraPosition(
574 scale_point(source, source.position, invert=True),
575 scale_point(source, source.focal_point, invert=True),
576 source.up,
577 )
578 self.Modified()
579 self.camera_set = True
580
581 @property
582 def bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
583 """Return the bounds of all VISIBLE actors present in the rendering window.
584
585 Actors with :attr:`~pyvista.Actor.visibility` or :attr:`~pyvista.Actor.use_bounds`
586 disabled are `not` included in the bounds.
587
588 .. versionchanged:: 0.45
589
590 Only the bounds of visible actors are now returned. Previously, the bounds
591 of all actors was returned, regardless of visibility.
592
593 Returns
594 -------
595 BoundsTuple
596 Bounds of all visible actors in the active renderer.
597
598 See Also
599 --------
600 compute_bounds
601 Compute the bounds with options to enable or disable actor visibility.
602
603 """
604 bounds = self.ComputeVisiblePropBounds()
605 return _fixup_bounds(bounds)
606
607 def compute_bounds(
608 self,
609 *,
610 force_visibility: bool = False,
611 force_use_bounds: bool = False,
612 ignore_actors: Sequence[str | _vtk.vtkProp | type[_vtk.vtkProp]] | None = None,
613 ) -> BoundsTuple:
614 """Return the bounds of actors present in the renderer.
615
616 By default, only visible actors are included in the bounds computation.
617 Optionally, the bounds of all actors may be computed, regardless if they
618 have their :attr:`~pyvista.Actor.visibility` or :attr:`~pyvista.Actor.use_bounds`
619 disabled. Specific actors may also be removed from the computation.
620
621 .. versionadded:: 0.45
622
623 Parameters
624 ----------
625 force_visibility : bool, default: False
626 Include actors with :attr:`~pyvista.Actor.visibility` disabled in the
627 computation. By default, invisible actors are excluded.
628
629 force_use_bounds : bool, default: False
630 Include actors with :attr:`~pyvista.Actor.use_bounds` disabled in the
631 computation. By default, actors with use bounds disabled are excluded.
632
633 ignore_actors : sequence[str | :vtk:`vtkProp` | type[:vtk:`vtkProp`]]
634 List of actors to ignore. The bounds of any actors included will be ignored.
635 Specify actors by name, type, or by instance.
636
637 Returns
638 -------
639 BoundsTuple
640 Bounds of selected actors in the active renderer.
641
642 See Also
643 --------
644 bounds
645 Bounds of all specified actors.
646
647 """
648 the_bounds = np.array([np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf])
649 if ignore_actors is None:
650 ignore_actors = []
651
652 ignored_types = [
653 actor_type for actor_type in ignore_actors if isinstance(actor_type, type)
654 ]
655
656 def _update_bounds(bounds) -> None:
657 def update_axis(ax) -> None:
658 the_bounds[ax * 2] = min(bounds[ax * 2], the_bounds[ax * 2])
659 the_bounds[ax * 2 + 1] = max(bounds[ax * 2 + 1], the_bounds[ax * 2 + 1])
660
661 for ax in range(3):
662 update_axis(ax)
663
664 for name, actor in self._actors.items():
665 if not actor.GetUseBounds() and not force_use_bounds:
666 continue
667 if not actor.GetVisibility() and not force_visibility:
668 continue
669 if ( # Check if the actor should be ignored
670 name in ignore_actors
671 or actor in ignore_actors
672 or any(isinstance(actor, actor_type) for actor_type in ignored_types)
673 ):
674 continue
675 if hasattr(actor, 'GetBounds') and (actor_bounds := actor.GetBounds()) is not None:
676 _update_bounds(actor_bounds)
677
678 return _fixup_bounds(the_bounds)
679
680 @property
681 def length(self): # numpydoc ignore=RT01
682 """Return the length of the diagonal of the bounding box of the scene.
683
684 Returns
685 -------
686 float
687 Length of the diagonal of the bounding box.
688
689 """
690 return pv.Box(self.bounds).length
691
692 @property
693 def center(self) -> tuple[float, float, float]:
694 """Return the center of the bounding box around all data present in the scene.
695
696 Returns
697 -------
698 tuple[float, float, float]
699 Cartesian coordinates of the center.
700
701 """
702 bnds = self.bounds
703 x = (bnds.x_max + bnds.x_min) / 2
704 y = (bnds.y_max + bnds.y_min) / 2
705 z = (bnds.z_max + bnds.z_min) / 2
706 return x, y, z
707
708 @property
709 def background_color(self): # numpydoc ignore=RT01
710 """Return the background color of this renderer."""
711 return Color(self.GetBackground())
712
713 @background_color.setter
714 def background_color(self, color) -> None:
715 self.set_background(color)
716 self.Modified()
717
718 def _before_render_event(self, *args, **kwargs) -> None:
719 """Notify all charts about render event."""
720 if self._charts is not None:
721 for chart in self._charts:
722 chart._render_event(*args, **kwargs)
723
724 def enable_depth_peeling(self, number_of_peels=None, occlusion_ratio=None):
725 """Enable depth peeling to improve rendering of translucent geometry.
726
727 Parameters
728 ----------
729 number_of_peels : int, optional
730 The maximum number of peeling layers. Initial value is 4
731 and is set in the ``pyvista.global_theme``. A special value of
732 0 means no maximum limit. It has to be a positive value.
733
734 occlusion_ratio : float, optional
735 The threshold under which the depth peeling algorithm
736 stops to iterate over peel layers. This is the ratio of
737 the number of pixels that have been touched by the last
738 layer over the total number of pixels of the viewport
739 area. Initial value is 0.0, meaning rendering has to be
740 exact. Greater values may speed up the rendering with
741 small impact on the quality.
742
743 Returns
744 -------
745 bool
746 If depth peeling is supported.
747
748 """
749 if number_of_peels is None:
750 number_of_peels = self._theme.depth_peeling.number_of_peels
751 if occlusion_ratio is None:
752 occlusion_ratio = self._theme.depth_peeling.occlusion_ratio
753 depth_peeling_supported = check_depth_peeling(number_of_peels, occlusion_ratio)
754 if depth_peeling_supported:
755 self.SetUseDepthPeeling(True)
756 self.SetMaximumNumberOfPeels(number_of_peels)
757 self.SetOcclusionRatio(occlusion_ratio)
758 self.Modified()
759 return depth_peeling_supported
760
761 def disable_depth_peeling(self) -> None:
762 """Disable depth peeling."""
763 self.SetUseDepthPeeling(False)
764 self.Modified()
765
766 def enable_anti_aliasing(self, aa_type='ssaa'):
767 """Enable anti-aliasing.
768
769 Parameters
770 ----------
771 aa_type : str, default: 'ssaa'
772 Anti-aliasing type. Either ``"fxaa"`` or ``"ssaa"``.
773
774 """
775 if not isinstance(aa_type, str):
776 msg = f'`aa_type` must be a string, not {type(aa_type)}'
777 raise TypeError(msg)
778 aa_type = aa_type.lower()
779
780 if aa_type == 'fxaa':
781 if uses_egl(): # pragma: no cover
782 # only display the warning when not building documentation
783 if not pv.BUILDING_GALLERY:
784 warn_external(
785 'VTK compiled with OSMesa/EGL does not properly support '
786 'FXAA anti-aliasing and SSAA will be used instead.',
787 )
788 self._render_passes.enable_ssaa_pass()
789 return
790 self._enable_fxaa()
791
792 elif aa_type == 'ssaa':
793 self._render_passes.enable_ssaa_pass()
794
795 else:
796 msg = f'Invalid `aa_type` "{aa_type}". Should be either "fxaa" or "ssaa"'
797 raise ValueError(msg)
798
799 def disable_anti_aliasing(self) -> None:
800 """Disable all anti-aliasing."""
801 self._render_passes.disable_ssaa_pass()
802 self.SetUseFXAA(False)
803 self.Modified()
804
805 def _enable_fxaa(self) -> None:
806 """Enable FXAA anti-aliasing."""
807 self.SetUseFXAA(True)
808 self.Modified()
809
810 def _disable_fxaa(self) -> None:
811 """Disable FXAA anti-aliasing."""
812 self.SetUseFXAA(False)
813 self.Modified()
814
815 def add_border(self, color='white', width=2.0):
816 """Add borders around the frame.
817
818 Parameters
819 ----------
820 color : ColorLike, default: "white"
821 Color of the border.
822
823 width : float, default: 2.0
824 Width of the border.
825
826 Returns
827 -------
828 :vtk:`vtkActor2D`
829 Border actor.
830
831 """
832 points = np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
833
834 lines = np.array([[2, 0, 1], [2, 1, 2], [2, 2, 3], [2, 3, 0]]).ravel()
835
836 poly = pv.PolyData()
837 poly.points = points
838 poly.lines = lines
839
840 coordinate = _vtk.vtkCoordinate()
841 coordinate.SetCoordinateSystemToNormalizedViewport()
842
843 mapper = _vtk.vtkPolyDataMapper2D()
844 mapper.SetInputData(poly)
845 mapper.SetTransformCoordinate(coordinate)
846
847 actor = _vtk.vtkActor2D()
848 actor.SetMapper(mapper)
849 actor.GetProperty().SetColor(Color(color).float_rgb)
850 actor.GetProperty().SetLineWidth(width)
851
852 self.AddViewProp(actor)
853 self.Modified()
854
855 self._border_actor = actor
856 return actor
857
858 @property
859 def has_border(self) -> bool: # numpydoc ignore=RT01
860 """Return if the renderer has a border."""
861 return self._border_actor is not None
862
863 @property
864 def border_width(self): # numpydoc ignore=RT01
865 """Return the border width."""
866 if self.has_border:
867 return self._border_actor.GetProperty().GetLineWidth() # type: ignore[union-attr]
868 return 0
869
870 @property
871 def border_color(self): # numpydoc ignore=RT01
872 """Return the border color."""
873 if self.has_border:
874 return Color(self._border_actor.GetProperty().GetColor()) # type: ignore[union-attr]
875 return None
876
877 def add_chart(self, chart, *charts):
878 """Add a chart to this renderer.
879
880 Parameters
881 ----------
882 chart : Chart
883 Chart to add to renderer.
884
885 *charts : Chart
886 Charts to add to renderer.
887
888 Examples
889 --------
890 >>> import pyvista as pv
891 >>> chart = pv.Chart2D()
892 >>> _ = chart.plot(range(10), range(10))
893 >>> pl = pv.Plotter()
894 >>> pl.add_chart(chart)
895 >>> pl.show()
896
897 """
898 # lazy instantiation here to avoid creating the charts object unless needed.
899 if self._charts is None:
900 self._charts = Charts(self)
901 self.AddObserver('StartEvent', partial(try_callback, self._before_render_event)) # type: ignore[arg-type]
902 self._charts.add_chart(chart, *charts)
903
904 @property
905 def has_charts(self): # numpydoc ignore=RT01
906 """Return whether this renderer has charts."""
907 return self._charts is not None and len(self._charts) > 0
908
909 def get_charts(self): # numpydoc ignore=RT01
910 """Return a list of all charts in this renderer.
911
912 Examples
913 --------
914 .. pyvista-plot::
915 :force_static:
916
917 >>> import pyvista as pv
918 >>> chart = pv.Chart2D()
919 >>> _ = chart.line([1, 2, 3], [0, 1, 0])
920 >>> pl = pv.Plotter()
921 >>> pl.add_chart(chart)
922 >>> chart is pl.renderer.get_charts()[0]
923 True
924
925 """
926 return [*self._charts] if self.has_charts else [] # type: ignore[misc]
927
928 @wraps(Charts.set_interaction)
929 @_deprecate_positional_args(allowed=['interactive'])
930 def set_chart_interaction( # numpydoc ignore=PR01,RT01
931 self,
932 interactive,
933 toggle=False, # noqa: FBT002
934 ):
935 """Wrap ``Charts.set_interaction``."""
936 return self._charts.set_interaction(interactive, toggle=toggle) if self.has_charts else [] # type: ignore[union-attr]
937
938 @wraps(Charts.get_charts_by_pos)
939 def _get_charts_by_pos(self, pos):
940 """Wrap ``Charts.get_charts_by_pos``."""
941 return self._charts.get_charts_by_pos(pos) if self.has_charts else [] # type: ignore[union-attr]
942
943 def remove_chart(self, chart_or_index) -> None:
944 """Remove a chart from this renderer.
945
946 Parameters
947 ----------
948 chart_or_index : Chart or int
949 Either the chart to remove from this renderer or its index in the collection of charts.
950
951 Examples
952 --------
953 First define a function to add two charts to a renderer.
954
955 >>> import pyvista as pv
956 >>> def plotter_with_charts():
957 ... pl = pv.Plotter()
958 ... pl.background_color = 'w'
959 ... chart_left = pv.Chart2D(size=(0.5, 1))
960 ... _ = chart_left.line([0, 1, 2], [2, 1, 3])
961 ... pl.add_chart(chart_left)
962 ... chart_right = pv.Chart2D(size=(0.5, 1), loc=(0.5, 0))
963 ... _ = chart_right.line([0, 1, 2], [3, 1, 2])
964 ... pl.add_chart(chart_right)
965 ... return pl, chart_left, chart_right
966 >>> pl, *_ = plotter_with_charts()
967 >>> pl.show()
968
969 Now reconstruct the same plotter but remove the right chart by index.
970
971 >>> pl, *_ = plotter_with_charts()
972 >>> pl.remove_chart(1)
973 >>> pl.show()
974
975 Finally, remove the left chart by reference.
976
977 >>> pl, chart_left, chart_right = plotter_with_charts()
978 >>> pl.remove_chart(chart_left)
979 >>> pl.show()
980
981 """
982 if self.has_charts:
983 cast('Charts', self._charts).remove_chart(chart_or_index)
984
985 @property
986 def actors(self) -> dict[str, _vtk.vtkProp]: # numpydoc ignore=RT01
987 """Return a dictionary of actors assigned to this renderer.
988
989 .. note::
990
991 This may include 2D actors such as :class:`~pyvista.Text`, 3D actors such
992 as :class:`~pyvista.Actor`, and assemblies such as :class:`~pyvista.AxesAssembly`.
993 The actors may also be unwrapped VTK objects.
994
995 """
996 return dict(self._actors.items())
997
998 @_deprecate_positional_args(allowed=['actor'])
999 def add_actor( # noqa: PLR0917
1000 self,
1001 actor,
1002 reset_camera=False, # noqa: FBT002
1003 name=None,
1004 culling=False, # noqa: FBT002
1005 pickable=True, # noqa: FBT002
1006 render=True, # noqa: FBT002
1007 remove_existing_actor=True, # noqa: FBT002
1008 ):
1009 """Add an actor to render window.
1010
1011 Creates an actor if input is a mapper.
1012
1013 Parameters
1014 ----------
1015 actor : :vtk:`vtkActor` | :vtk:`vtkMapper` | Actor
1016 The actor to be added. Can be either :vtk:`vtkActor` or :vtk:`vtkMapper`.
1017
1018 reset_camera : bool, default: False
1019 Resets the camera when ``True``.
1020
1021 name : str, optional
1022 Name to assign to the actor. Defaults to the memory address.
1023
1024 culling : str, default: False
1025 Does not render faces that are culled. Options are
1026 ``'front'`` or ``'back'``. This can be helpful for dense
1027 surface meshes, especially when edges are visible, but can
1028 cause flat meshes to be partially displayed.
1029
1030 pickable : bool, default: True
1031 Whether to allow this actor to be pickable within the
1032 render window.
1033
1034 render : bool, default: True
1035 If the render window is being shown, trigger a render
1036 after adding the actor.
1037
1038 remove_existing_actor : bool, default: True
1039 Removes any existing actor if the named actor ``name`` is already
1040 present.
1041
1042 Returns
1043 -------
1044 actor : :vtk:`vtkActor` | Actor
1045 The actor.
1046
1047 actor_properties : vtk.Properties
1048 Actor properties.
1049
1050 """
1051 # Remove actor by that name if present
1052 rv = None
1053 if name and remove_existing_actor:
1054 rv = self.remove_actor(name, reset_camera=False, render=False)
1055
1056 if isinstance(actor, _vtk.vtkMapper):
1057 actor = Actor(mapper=actor, name=name)
1058
1059 if name is None:
1060 name = (
1061 actor.name
1062 if (hasattr(actor, 'name') and actor.name)
1063 else f'{type(actor).__name__}({actor.GetAddressAsString("")})'
1064 )
1065 actor.name = name
1066 actor.SetPickable(pickable)
1067 # Apply this renderer's scale to the actor (which can be further scaled)
1068 if hasattr(actor, 'SetScale'):
1069 actor.SetScale(np.array(actor.GetScale()) * np.array(self.scale))
1070 self.AddActor(actor) # must add actor before resetting camera
1071
1072 if reset_camera or (not self.camera_set and reset_camera is None and not rv):
1073 self.reset_camera(render=render)
1074 elif render:
1075 self.parent.render()
1076
1077 self.update_bounds_axes()
1078
1079 if isinstance(culling, str):
1080 culling = culling.lower()
1081
1082 if culling:
1083 if culling in [True, 'back', 'backface', 'b']:
1084 with contextlib.suppress(AttributeError):
1085 actor.GetProperty().BackfaceCullingOn()
1086 elif culling in ['front', 'frontface', 'f']:
1087 with contextlib.suppress(AttributeError):
1088 actor.GetProperty().FrontfaceCullingOn()
1089 else:
1090 msg = f'Culling option ({culling}) not understood.'
1091 raise ValueError(msg)
1092
1093 self.Modified()
1094
1095 prop = None
1096 if hasattr(actor, 'GetProperty'):
1097 prop = actor.GetProperty()
1098
1099 return actor, prop
1100
1101 @_deprecate_positional_args
1102 def add_axes_at_origin( # noqa: PLR0917
1103 self,
1104 x_color=None,
1105 y_color=None,
1106 z_color=None,
1107 xlabel='X',
1108 ylabel='Y',
1109 zlabel='Z',
1110 line_width=2,
1111 labels_off=False, # noqa: FBT002
1112 ):
1113 """Add axes actor at origin.
1114
1115 Parameters
1116 ----------
1117 x_color : ColorLike, optional
1118 The color of the x axes arrow.
1119
1120 y_color : ColorLike, optional
1121 The color of the y axes arrow.
1122
1123 z_color : ColorLike, optional
1124 The color of the z axes arrow.
1125
1126 xlabel : str, default: "X"
1127 The label of the x axes arrow.
1128
1129 ylabel : str, default: "Y"
1130 The label of the y axes arrow.
1131
1132 zlabel : str, default: "Z"
1133 The label of the z axes arrow.
1134
1135 line_width : int, default: 2
1136 Width of the arrows.
1137
1138 labels_off : bool, default: False
1139 Disables the label text when ``True``.
1140
1141 Returns
1142 -------
1143 :vtk:`vtkAxesActor`
1144 Actor of the axes.
1145
1146 See Also
1147 --------
1148 add_axes
1149
1150 :ref:`axes_objects_example`
1151 Example showing different axes objects.
1152
1153 Examples
1154 --------
1155 >>> import pyvista as pv
1156 >>> pl = pv.Plotter()
1157 >>> _ = pl.add_mesh(pv.Sphere(center=(2, 0, 0)), color='r')
1158 >>> _ = pl.add_mesh(pv.Sphere(center=(0, 2, 0)), color='g')
1159 >>> _ = pl.add_mesh(pv.Sphere(center=(0, 0, 2)), color='b')
1160 >>> _ = pl.add_axes_at_origin()
1161 >>> pl.show()
1162
1163 """
1164 marker = create_axes_marker(
1165 line_width=line_width,
1166 x_color=x_color,
1167 y_color=y_color,
1168 z_color=z_color,
1169 xlabel=xlabel,
1170 ylabel=ylabel,
1171 zlabel=zlabel,
1172 labels_off=labels_off,
1173 )
1174 self.AddActor(marker)
1175 self.Modified()
1176 self._marker_actor = marker
1177 return marker
1178
1179 def _remove_axes_widget(self):
1180 """Remove and delete the current axes widget."""
1181 if self.axes_widget is not None:
1182 self.axes_actor = None
1183 # HACK: set the viewport to a tiny value to hide the widget first
1184 # This is due to an issue with a blue box appearing after removal
1185 # Tracked in https://gitlab.kitware.com/vtk/vtk/-/issues/19592
1186 self.axes_widget.SetViewport(0.0, 0.0, 0.0001, 0.0001)
1187 if self.axes_widget.GetEnabled():
1188 self.axes_widget.EnabledOff()
1189 self.Modified()
1190 self.axes_widget = None
1191
1192 @_deprecate_positional_args(allowed=['actor'])
1193 def add_orientation_widget( # noqa: PLR0917
1194 self,
1195 actor,
1196 interactive=None,
1197 color=None,
1198 opacity=1.0,
1199 viewport=None,
1200 ):
1201 """Use the given actor in an orientation marker widget.
1202
1203 Color and opacity are only valid arguments if a mesh is passed.
1204
1205 Parameters
1206 ----------
1207 actor : :vtk:`vtkActor` | DataSet
1208 The mesh or actor to use as the marker.
1209
1210 interactive : bool, optional
1211 Control if the orientation widget is interactive. By
1212 default uses the value from
1213 :attr:`pyvista.global_theme.interactive
1214 <pyvista.plotting.themes.Theme.interactive>`.
1215
1216 color : ColorLike, optional
1217 The color of the actor. This only applies if ``actor`` is
1218 a :class:`pyvista.DataSet`.
1219
1220 opacity : int | float, default: 1.0
1221 Opacity of the marker.
1222
1223 viewport : sequence[float], optional
1224 Viewport ``(xstart, ystart, xend, yend)`` of the widget.
1225
1226 Returns
1227 -------
1228 :vtk:`vtkOrientationMarkerWidget`
1229 Orientation marker widget.
1230
1231 See Also
1232 --------
1233 add_axes
1234 Add arrow-style axes as an orientation widget.
1235
1236 add_box_axes
1237 Add an axes box as an orientation widget.
1238
1239 add_north_arrow_widget
1240 Add north arrow as an orientation widget.
1241
1242 :ref:`axes_objects_example`
1243 Example showing different axes objects.
1244
1245 Examples
1246 --------
1247 Use an Arrow as the orientation widget.
1248
1249 >>> import pyvista as pv
1250 >>> pl = pv.Plotter()
1251 >>> actor = pl.add_mesh(pv.Cube(), show_edges=True)
1252 >>> widget = pl.add_orientation_widget(pv.Arrow(), color='r')
1253 >>> pl.show()
1254
1255 """
1256 if isinstance(actor, pv.DataSet):
1257 mapper = _vtk.vtkDataSetMapper()
1258 mesh = actor.copy()
1259 mesh.clear_data()
1260 mapper.SetInputData(mesh)
1261 actor = pv.Actor(mapper=mapper)
1262 if color is not None:
1263 actor.prop.color = color
1264 actor.prop.opacity = opacity
1265 self._remove_axes_widget()
1266 if interactive is None:
1267 interactive = self._theme.interactive
1268 axes_widget = _vtk.vtkOrientationMarkerWidget()
1269 self.axes_widget = axes_widget
1270 axes_widget.SetOrientationMarker(actor)
1271 if self.parent.iren is not None:
1272 axes_widget.SetInteractor(self.parent.iren.interactor)
1273 axes_widget.SetEnabled(1)
1274 axes_widget.SetInteractive(interactive)
1275 axes_widget.SetCurrentRenderer(self)
1276 if viewport is not None:
1277 axes_widget.SetViewport(viewport)
1278 self.Modified()
1279 return axes_widget
1280
1281 @_deprecate_positional_args
1282 def add_axes( # noqa: PLR0917
1283 self,
1284 interactive=None,
1285 line_width=2,
1286 color=None,
1287 x_color=None,
1288 y_color=None,
1289 z_color=None,
1290 xlabel='X',
1291 ylabel='Y',
1292 zlabel='Z',
1293 labels_off=False, # noqa: FBT002
1294 viewport=(0, 0, 0.2, 0.2),
1295 **kwargs,
1296 ):
1297 """Add an interactive axes widget in the bottom left corner.
1298
1299 Parameters
1300 ----------
1301 interactive : bool, optional
1302 Enable this orientation widget to be moved by the user.
1303
1304 line_width : int, default: 2
1305 The width of the marker lines.
1306
1307 color : ColorLike, optional
1308 Color of the labels.
1309
1310 x_color : ColorLike, optional
1311 Color used for the x-axis arrow. Defaults to theme axes parameters.
1312
1313 y_color : ColorLike, optional
1314 Color used for the y-axis arrow. Defaults to theme axes parameters.
1315
1316 z_color : ColorLike, optional
1317 Color used for the z-axis arrow. Defaults to theme axes parameters.
1318
1319 xlabel : str, default: "X"
1320 Text used for the x-axis.
1321
1322 ylabel : str, default: "Y"
1323 Text used for the y-axis.
1324
1325 zlabel : str, default: "Z"
1326 Text used for the z-axis.
1327
1328 labels_off : bool, default: False
1329 Enable or disable the text labels for the axes.
1330
1331 viewport : sequence[float], default: (0, 0, 0.2, 0.2)
1332 Viewport ``(xstart, ystart, xend, yend)`` of the widget.
1333
1334 **kwargs : dict, optional
1335 Used for passing parameters for the orientation marker
1336 widget. See the parameters of :func:`pyvista.create_axes_marker`.
1337
1338 Returns
1339 -------
1340 AxesActor
1341 Axes actor of the added widget.
1342
1343 See Also
1344 --------
1345 show_axes
1346 Similar method which calls :func:`add_axes` without any parameters.
1347
1348 add_axes_at_origin
1349 Add an :class:`pyvista.AxesActor` to the origin of a scene.
1350
1351 add_box_axes
1352 Add an axes box as an orientation widget.
1353
1354 add_north_arrow_widget
1355 Add north arrow as an orientation widget.
1356
1357 add_orientation_widget
1358 Add any actor as an orientation widget.
1359
1360 :ref:`axes_objects_example`
1361 Example showing different axes objects.
1362
1363 Examples
1364 --------
1365 Show axes without labels and with thick lines.
1366
1367 >>> import pyvista as pv
1368 >>> pl = pv.Plotter()
1369 >>> actor = pl.add_mesh(pv.Box(), show_edges=True)
1370 >>> _ = pl.add_axes(line_width=5, labels_off=True)
1371 >>> pl.show()
1372
1373 Specify more parameters for the axes marker.
1374
1375 >>> import pyvista as pv
1376 >>> pl = pv.Plotter()
1377 >>> actor = pl.add_mesh(pv.Box(), show_edges=True)
1378 >>> _ = pl.add_axes(
1379 ... line_width=5,
1380 ... cone_radius=0.6,
1381 ... shaft_length=0.7,
1382 ... tip_length=0.3,
1383 ... ambient=0.5,
1384 ... label_size=(0.4, 0.16),
1385 ... )
1386 >>> pl.show()
1387
1388 """
1389 if interactive is None:
1390 interactive = self._theme.interactive
1391 self._remove_axes_widget()
1392
1393 self.axes_actor = create_axes_marker(
1394 label_color=color,
1395 line_width=line_width,
1396 x_color=x_color,
1397 y_color=y_color,
1398 z_color=z_color,
1399 xlabel=xlabel,
1400 ylabel=ylabel,
1401 zlabel=zlabel,
1402 labels_off=labels_off,
1403 **kwargs,
1404 )
1405 axes_widget = self.add_orientation_widget(
1406 self.axes_actor,
1407 interactive=interactive,
1408 color=None,
1409 )
1410 axes_widget.SetViewport(viewport)
1411 return self.axes_actor
1412
1413 @_deprecate_positional_args
1414 def add_north_arrow_widget( # noqa: PLR0917
1415 self,
1416 interactive=None,
1417 color='#4169E1',
1418 opacity=1.0,
1419 line_width=2,
1420 edge_color=None,
1421 lighting=False, # noqa: FBT002
1422 viewport=(0, 0, 0.1, 0.1),
1423 *,
1424 top_color=None,
1425 bottom_color=None,
1426 ):
1427 """Add a geographic north arrow to the scene.
1428
1429 .. versionadded:: 0.44.0
1430
1431 Parameters
1432 ----------
1433 interactive : bool, optional
1434 Control if the orientation widget is interactive. By
1435 default uses the value from
1436 :attr:`pyvista.global_theme.interactive
1437 <pyvista.plotting.themes.Theme.interactive>`.
1438
1439 color : ColorLike, optional
1440 Color of the north arrow. When ``top_color`` or ``bottom_color``
1441 is set, this color is applied to the side faces only.
1442
1443 opacity : float, optional
1444 Opacity of the north arrow.
1445
1446 line_width : float, optional
1447 Width of the north edge arrow lines.
1448
1449 edge_color : ColorLike, optional
1450 Color of the edges.
1451
1452 lighting : bool, optional
1453 Enable or disable lighting on north arrow.
1454
1455 viewport : sequence[float], default: (0, 0, 0.1, 0.1)
1456 Viewport ``(xstart, ystart, xend, yend)`` of the widget.
1457
1458 top_color : ColorLike, optional
1459 Color applied to the top face of the arrow. When set (together
1460 with or independently from ``bottom_color``), per-face RGB
1461 scalars are used so the top face can be distinguished from the
1462 bottom at a glance. Defaults to ``color`` when only
1463 ``bottom_color`` is set.
1464
1465 .. versionadded:: 0.48.0
1466
1467 bottom_color : ColorLike, optional
1468 Color applied to the bottom face of the arrow. See ``top_color``
1469 for details.
1470
1471 .. versionadded:: 0.48.0
1472
1473 Returns
1474 -------
1475 :vtk:`vtkOrientationMarkerWidget`
1476 Orientation marker widget.
1477
1478 See Also
1479 --------
1480 add_axes
1481 Add arrow-style axes as an orientation widget.
1482
1483 add_box_axes
1484 Add an axes box as an orientation widget.
1485
1486 add_orientation_widget
1487 Add a custom mesh as an orientation widget.
1488
1489 :ref:`axes_objects_example`
1490 Example showing different axes objects.
1491
1492 Examples
1493 --------
1494 Use a north arrow as the orientation widget.
1495
1496 >>> import pyvista as pv
1497 >>> from pyvista import examples
1498 >>> terrain = examples.download_st_helens().warp_by_scalar()
1499 >>> pl = pv.Plotter()
1500 >>> actor = pl.add_mesh(terrain)
1501 >>> widget = pl.add_north_arrow_widget()
1502 >>> pl.enable_terrain_style(mouse_wheel_zooms=True)
1503 >>> pl.show()
1504
1505 Distinguish the top and bottom of the arrow by coloring the top
1506 face a lighter shade and the bottom face a darker shade of the
1507 side color.
1508
1509 >>> pl = pv.Plotter()
1510 >>> _ = pl.add_mesh(pv.Sphere())
1511 >>> widget = pl.add_north_arrow_widget(
1512 ... color='royalblue',
1513 ... top_color='lightsteelblue',
1514 ... bottom_color='midnightblue',
1515 ... )
1516 >>> pl.show()
1517
1518 """
1519 marker = create_north_arrow()
1520 mapper = pv.DataSetMapper(marker)
1521 actor = pv.Actor(mapper)
1522 actor.prop.show_edges = True
1523 if edge_color is not None:
1524 actor.prop.edge_color = edge_color
1525 actor.prop.line_width = line_width
1526 actor.prop.opacity = opacity
1527 actor.prop.lighting = lighting
1528 if top_color is None and bottom_color is None:
1529 actor.prop.color = color
1530 else:
1531 # Face order in create_north_arrow: 4 sides, bottom (z=0), top (z=1).
1532 top = top_color if top_color is not None else color
1533 bottom = bottom_color if bottom_color is not None else color
1534 face_colors = [color, color, color, color, bottom, top]
1535 marker.cell_data['_face_index'] = np.arange(marker.n_cells, dtype=np.uint8)
1536 marker.color_labels(
1537 face_colors,
1538 scalars='_face_index',
1539 coloring_mode='index',
1540 inplace=True,
1541 )
1542 mapper.color_mode = 'direct'
1543 return self.add_orientation_widget(
1544 actor,
1545 interactive=interactive,
1546 viewport=viewport,
1547 )
1548
1549 def add_box_axes(
1550 self,
1551 *,
1552 interactive=None,
1553 line_width=2,
1554 text_scale=0.366667,
1555 edge_color='black',
1556 x_color=None,
1557 y_color=None,
1558 z_color=None,
1559 xlabel='X',
1560 ylabel='Y',
1561 zlabel='Z',
1562 x_face_color='white',
1563 y_face_color='white',
1564 z_face_color='white',
1565 label_color=None,
1566 labels_off=False,
1567 opacity=0.5,
1568 show_text_edges=False,
1569 viewport=(0, 0, 0.2, 0.2),
1570 ):
1571 """Add an interactive color box axes widget in the bottom left corner.
1572
1573 Parameters
1574 ----------
1575 interactive : bool, optional
1576 Enable this orientation widget to be moved by the user.
1577
1578 line_width : float, optional
1579 The width of the marker lines.
1580
1581 text_scale : float, optional
1582 Size of the text relative to the faces.
1583
1584 edge_color : ColorLike, optional
1585 Color of the edges.
1586
1587 x_color : ColorLike, optional
1588 Color of the x-axis text.
1589
1590 y_color : ColorLike, optional
1591 Color of the y-axis text.
1592
1593 z_color : ColorLike, optional
1594 Color of the z-axis text.
1595
1596 xlabel : str, optional
1597 Text used for the x-axis.
1598
1599 ylabel : str, optional
1600 Text used for the y-axis.
1601
1602 zlabel : str, optional
1603 Text used for the z-axis.
1604
1605 x_face_color : ColorLike, optional
1606 Color used for the x-axis arrow. Defaults to theme axes
1607 parameters.
1608
1609 y_face_color : ColorLike, optional
1610 Color used for the y-axis arrow. Defaults to theme axes
1611 parameters.
1612
1613 z_face_color : ColorLike, optional
1614 Color used for the z-axis arrow. Defaults to theme axes
1615 parameters.
1616
1617 label_color : ColorLike, optional
1618 Color of the labels.
1619
1620 labels_off : bool, optional
1621 Enable or disable the text labels for the axes.
1622
1623 opacity : float, optional
1624 Opacity in the range of ``[0, 1]`` of the orientation box.
1625
1626 show_text_edges : bool, optional
1627 Enable or disable drawing the vector text edges.
1628
1629 viewport : sequence[float], default: (0, 0, 0.2, 0.2)
1630 Viewport ``(xstart, ystart, xend, yend)`` of the widget.
1631
1632 Returns
1633 -------
1634 :vtk:`vtkAnnotatedCubeActor`
1635 Axes actor.
1636
1637 See Also
1638 --------
1639 add_axes
1640 Add arrow-style axes as an orientation widget.
1641
1642 add_north_arrow_widget
1643 Add north arrow as an orientation widget.
1644
1645 add_orientation_widget
1646 Add any actor as an orientation widget.
1647
1648 :ref:`axes_objects_example`
1649 Example showing different axes objects.
1650
1651 Examples
1652 --------
1653 Use the axes orientation widget instead of the default arrows.
1654
1655 >>> import pyvista as pv
1656 >>> pl = pv.Plotter()
1657 >>> _ = pl.add_mesh(pv.Sphere())
1658 >>> _ = pl.add_box_axes()
1659 >>> pl.show()
1660
1661 """
1662 if interactive is None:
1663 interactive = self._theme.interactive
1664 self._remove_axes_widget()
1665 self.axes_actor = create_axes_orientation_box(
1666 line_width=line_width,
1667 text_scale=text_scale,
1668 edge_color=edge_color,
1669 x_color=x_color,
1670 y_color=y_color,
1671 z_color=z_color,
1672 xlabel=xlabel,
1673 ylabel=ylabel,
1674 zlabel=zlabel,
1675 x_face_color=x_face_color,
1676 y_face_color=y_face_color,
1677 z_face_color=z_face_color,
1678 color_box=True,
1679 label_color=label_color,
1680 labels_off=labels_off,
1681 opacity=opacity,
1682 show_text_edges=show_text_edges,
1683 )
1684 axes_widget = self.add_orientation_widget(
1685 self.axes_actor,
1686 interactive=interactive,
1687 color=None,
1688 )
1689 axes_widget.SetViewport(viewport)
1690 return self.axes_actor
1691
1692 def hide_axes(self) -> None:
1693 """Hide the axes orientation widget.
1694
1695 See Also
1696 --------
1697 show_axes
1698 Show the axes orientation widget.
1699
1700 axes_enabled
1701 Check if the axes orientation widget is enabled.
1702
1703 Examples
1704 --------
1705 >>> import pyvista as pv
1706 >>> pl = pv.Plotter()
1707 >>> pl.hide_axes()
1708
1709 """
1710 if self.axes_widget is not None and self.axes_widget.GetEnabled():
1711 self.axes_widget.EnabledOff()
1712 self.Modified()
1713
1714 def show_axes(self) -> None:
1715 """Show the axes orientation widget.
1716
1717 See Also
1718 --------
1719 add_axes
1720 Similar method with additional options.
1721
1722 hide_axes
1723 Hide the axes orientation widget.
1724
1725 axes_enabled
1726 Check if the axes orientation widget is enabled.
1727
1728 add_axes_at_origin
1729 Add a :class:`pyvista.AxesActor` to the origin of a scene.
1730
1731 Examples
1732 --------
1733 >>> import pyvista as pv
1734 >>> pl = pv.Plotter()
1735 >>> pl.show_axes()
1736
1737 """
1738 if self.axes_widget is not None:
1739 self.axes_widget.EnabledOn()
1740 self.axes_widget.SetCurrentRenderer(self)
1741 else:
1742 self.add_axes()
1743 self.Modified()
1744
1745 @property
1746 def axes_enabled(self):
1747 """Return ``True`` when the axes widget is enabled.
1748
1749 See Also
1750 --------
1751 show_axes
1752 Show the axes orientation widget.
1753
1754 hide_axes
1755 Hide the axes orientation widget.
1756
1757 Examples
1758 --------
1759 >>> import pyvista as pv
1760 >>> pl = pv.Plotter()
1761 >>> pl.hide_axes()
1762 >>> pl.renderer.axes_enabled
1763 False
1764
1765 Returns
1766 -------
1767 bool
1768 Return ``True`` when the axes widget is enabled.
1769
1770 """
1771 if self.axes_widget is not None:
1772 return bool(self.axes_widget.GetEnabled())
1773 return False
1774
1775 @_deprecate_positional_args
1776 def show_bounds( # noqa: PLR0917
1777 self,
1778 mesh=None,
1779 bounds=None,
1780 axes_ranges=None,
1781 show_xaxis=True, # noqa: FBT002
1782 show_yaxis=True, # noqa: FBT002
1783 show_zaxis=True, # noqa: FBT002
1784 show_xlabels=True, # noqa: FBT002
1785 show_ylabels=True, # noqa: FBT002
1786 show_zlabels=True, # noqa: FBT002
1787 bold=True, # noqa: FBT002
1788 font_size=None,
1789 font_family=None,
1790 color=None,
1791 xtitle='X Axis',
1792 ytitle='Y Axis',
1793 ztitle='Z Axis',
1794 n_xlabels=5,
1795 n_ylabels=5,
1796 n_zlabels=5,
1797 use_2d=False, # noqa: FBT002
1798 grid=None,
1799 location='closest',
1800 ticks=None,
1801 all_edges=False, # noqa: FBT002
1802 corner_factor=0.5,
1803 fmt=None,
1804 minor_ticks=False, # noqa: FBT002
1805 padding=0.0,
1806 use_3d_text: bool | None = None, # noqa: FBT001
1807 render=None,
1808 **kwargs,
1809 ):
1810 """Add bounds axes.
1811
1812 Shows the bounds of the most recent input mesh unless mesh is
1813 specified.
1814
1815 Parameters
1816 ----------
1817 mesh : pyvista.DataSet | pyvista.MultiBlock, optional
1818 Input mesh to draw bounds axes around.
1819
1820 bounds : sequence[float], optional
1821 Bounds to override mesh bounds in the form ``[xmin, xmax,
1822 ymin, ymax, zmin, zmax]``.
1823
1824 axes_ranges : sequence[float], optional
1825 When set, these values override the values that are shown on the
1826 axes. This can be useful when plotting scaled datasets or if you wish
1827 to manually display different values. These values must be in the
1828 form:
1829
1830 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
1831
1832 show_xaxis : bool, default: True
1833 Makes x-axis visible.
1834
1835 show_yaxis : bool, default: True
1836 Makes y-axis visible.
1837
1838 show_zaxis : bool, default: True
1839 Makes z-axis visible.
1840
1841 show_xlabels : bool, default: True
1842 Shows X labels.
1843
1844 show_ylabels : bool, default: True
1845 Shows Y labels.
1846
1847 show_zlabels : bool, default: True
1848 Shows Z labels.
1849
1850 bold : bool, default: True
1851 Bolds axis labels and numbers.
1852
1853 font_size : float, optional
1854 Sets the size of the label font. Defaults to
1855 :attr:`pyvista.global_theme.font.size
1856 <pyvista.plotting.themes._Font.size>`.
1857
1858 font_family : str, optional
1859 Font family. Must be either ``'courier'``, ``'times'``,
1860 or ``'arial'``. Defaults to :attr:`pyvista.global_theme.font.family
1861 <pyvista.plotting.themes._Font.family>`.
1862
1863 color : ColorLike, optional
1864 Color of all labels and axis titles. Defaults to
1865 :attr:`pyvista.global_theme.font.color
1866 <pyvista.plotting.themes._Font.color>`.
1867
1868 Either a string, RGB list, or hex color string. For
1869 example:
1870
1871 * ``color='white'``
1872 * ``color='w'``
1873 * ``color=[1.0, 1.0, 1.0]``
1874 * ``color='#FFFFFF'``
1875
1876 xtitle : str, default: "X Axis"
1877 Title of the x-axis. Default ``"X Axis"``.
1878
1879 ytitle : str, default: "Y Axis"
1880 Title of the y-axis. Default ``"Y Axis"``.
1881
1882 ztitle : str, default: "Z Axis"
1883 Title of the z-axis. Default ``"Z Axis"``.
1884
1885 n_xlabels : int, default: 5
1886 Number of labels for the x-axis.
1887
1888 n_ylabels : int, default: 5
1889 Number of labels for the y-axis.
1890
1891 n_zlabels : int, default: 5
1892 Number of labels for the z-axis.
1893
1894 use_2d : bool, default: False
1895 This can be enabled for smoother plotting.
1896
1897 grid : bool or str, optional
1898 Add grid lines to the backface (``True``, ``'back'``, or
1899 ``'backface'``) or to the frontface (``'front'``,
1900 ``'frontface'``) of the axes actor.
1901
1902 location : str, default: "closest"
1903 Set how the axes are drawn: either static (``'all'``), closest
1904 triad (``'front'``, ``'closest'``, ``'default'``), furthest triad
1905 (``'back'``, ``'furthest'``), static closest to the origin
1906 (``'origin'``), or outer edges (``'outer'``) in relation to the
1907 camera position.
1908
1909 ticks : str, optional
1910 Set how the ticks are drawn on the axes grid. Options include:
1911 ``'inside', 'outside', 'both'``.
1912
1913 all_edges : bool, default: False
1914 Adds an unlabeled and unticked box at the boundaries of
1915 plot. Useful for when wanting to plot outer grids while
1916 still retaining all edges of the boundary.
1917
1918 corner_factor : float, default: 0.5
1919 If ``all_edges``, this is the factor along each axis to
1920 draw the default box. Default shows the full box.
1921
1922 fmt : str, optional
1923 A format string defining how tick labels are generated from
1924 tick positions. A default is looked up on the active theme.
1925
1926 minor_ticks : bool, default: False
1927 If ``True``, also plot minor ticks on all axes.
1928
1929 padding : float, default: 0.0
1930 An optional percent padding along each axial direction to
1931 cushion the datasets in the scene from the axes
1932 annotations. Defaults no padding.
1933
1934 use_3d_text : bool
1935 Use :vtk:`vtkTextActor3D` for titles and labels. Defaults to ``False`` for
1936 VTK 9.6 and later, and ``True`` for older versions of VTK.
1937
1938 .. versionchanged:: 0.47
1939 The default value of this flag is now dependent on the version of VTK used.
1940 Previously, the default was always ``True``.
1941
1942 .. warning::
1943 Setting ``use_3d_text=True`` is not recommended with VTK 9.6.0 or later since
1944 the 3D labels may not render at all in some cases. This is a known VTK bug:
1945 https://gitlab.kitware.com/vtk/vtk/-/issues/19729.
1946
1947 render : bool, optional
1948 If the render window is being shown, trigger a render
1949 after showing bounds.
1950
1951 **kwargs : dict, optional
1952 Deprecated keyword arguments.
1953
1954 Returns
1955 -------
1956 pyvista.CubeAxesActor
1957 Bounds actor.
1958
1959 See Also
1960 --------
1961 show_grid
1962 remove_bounds_axes
1963 update_bounds_axes
1964
1965 :ref:`axes_objects_example`
1966 Example showing different axes objects.
1967 :ref:`bounds_example`
1968 Additional examples using this method.
1969
1970 Examples
1971 --------
1972 >>> import pyvista as pv
1973 >>> from pyvista import examples
1974
1975 >>> mesh = pv.Sphere()
1976 >>> pl = pv.Plotter()
1977 >>> actor = pl.add_mesh(mesh)
1978 >>> actor = pl.show_bounds(
1979 ... grid='front',
1980 ... location='outer',
1981 ... all_edges=True,
1982 ... )
1983 >>> pl.show()
1984
1985 Control how many labels are displayed.
1986
1987 >>> mesh = examples.load_random_hills()
1988
1989 >>> pl = pv.Plotter()
1990 >>> actor = pl.add_mesh(mesh, cmap='terrain', show_scalar_bar=False)
1991 >>> actor = pl.show_bounds(
1992 ... grid='back',
1993 ... location='outer',
1994 ... ticks='both',
1995 ... n_xlabels=2,
1996 ... n_ylabels=2,
1997 ... n_zlabels=2,
1998 ... xtitle='Easting',
1999 ... ytitle='Northing',
2000 ... ztitle='Elevation',
2001 ... )
2002 >>> pl.show()
2003
2004 Hide labels, but still show axis titles.
2005
2006 >>> pl = pv.Plotter()
2007 >>> actor = pl.add_mesh(mesh, cmap='terrain', show_scalar_bar=False)
2008 >>> actor = pl.show_bounds(
2009 ... grid='back',
2010 ... location='outer',
2011 ... ticks='both',
2012 ... show_xlabels=False,
2013 ... show_ylabels=False,
2014 ... show_zlabels=False,
2015 ... xtitle='Easting',
2016 ... ytitle='Northing',
2017 ... ztitle='Elevation',
2018 ... )
2019 >>> pl.show()
2020
2021 """
2022 self.remove_bounds_axes()
2023
2024 vtk_less_than_96 = pv.vtk_version_info < (9, 6, 0)
2025 if use_3d_text is None:
2026 # Use 2D for VTK 9.6 since 3D is broken https://gitlab.kitware.com/vtk/vtk/-/issues/19729
2027 use_3d_text = vtk_less_than_96
2028 if font_family is None:
2029 font_family = self._theme.font.family
2030 if font_size is None:
2031 font_size = self._theme.font.size
2032 if fmt is None:
2033 fmt = self._theme.font.fmt
2034 if fmt is None:
2035 fmt = '%.1f' if vtk_less_than_96 else '{0:.1f}' # fallback
2036
2037 if 'xlabel' in kwargs: # pragma: no cover
2038 xtitle = kwargs.pop('xlabel')
2039 warn_external(
2040 '`xlabel` is deprecated. Use `xtitle` instead.', PyVistaDeprecationWarning
2041 )
2042 if 'ylabel' in kwargs: # pragma: no cover
2043 ytitle = kwargs.pop('ylabel')
2044 warn_external(
2045 '`ylabel` is deprecated. Use `ytitle` instead.', PyVistaDeprecationWarning
2046 )
2047 if 'zlabel' in kwargs: # pragma: no cover
2048 ztitle = kwargs.pop('zlabel')
2049 warn_external(
2050 '`zlabel` is deprecated. Use `ztitle` instead.', PyVistaDeprecationWarning
2051 )
2052 assert_empty_kwargs(**kwargs)
2053
2054 color = Color(color, default_color=self._theme.font.color)
2055
2056 if mesh is None and bounds is None:
2057 # Use the bounds of all data in the rendering window
2058 bounds = np.array(self.bounds)
2059 elif bounds is None:
2060 # otherwise, use the bounds of the mesh (if available)
2061 bounds = np.array(mesh.bounds)
2062 else:
2063 bounds = np.asanyarray(bounds, dtype=float)
2064
2065 # create actor
2066 cube_axes_actor = pv.CubeAxesActor(
2067 self.camera,
2068 minor_ticks=minor_ticks,
2069 tick_location=ticks,
2070 x_title=xtitle,
2071 y_title=ytitle,
2072 z_title=ztitle,
2073 x_axis_visibility=show_xaxis,
2074 y_axis_visibility=show_yaxis,
2075 z_axis_visibility=show_zaxis,
2076 x_label_format=fmt,
2077 y_label_format=fmt,
2078 z_label_format=fmt,
2079 x_label_visibility=show_xlabels,
2080 y_label_visibility=show_ylabels,
2081 z_label_visibility=show_zlabels,
2082 n_xlabels=n_xlabels,
2083 n_ylabels=n_ylabels,
2084 n_zlabels=n_zlabels,
2085 )
2086
2087 cube_axes_actor.use_2d_mode = use_2d or not np.allclose(self.scale, [1.0, 1.0, 1.0])
2088
2089 if grid:
2090 grid = 'back' if grid is True else grid
2091 if not isinstance(grid, str):
2092 msg = f'`grid` must be a str, not {type(grid)}'
2093 raise TypeError(msg)
2094 grid = grid.lower()
2095 if grid in ('front', 'frontface'):
2096 cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_CLOSEST)
2097 elif grid in ('both', 'all'):
2098 cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_ALL)
2099 elif grid in ('back', True):
2100 cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST)
2101 else:
2102 msg = f'`grid` must be either "front", "back, or, "all", not {grid}'
2103 raise ValueError(msg)
2104 # Only show user desired grid lines
2105 cube_axes_actor.SetDrawXGridlines(show_xaxis)
2106 cube_axes_actor.SetDrawYGridlines(show_yaxis)
2107 cube_axes_actor.SetDrawZGridlines(show_zaxis)
2108 # Set the colors
2109 cube_axes_actor.GetXAxesGridlinesProperty().SetColor(color.float_rgb)
2110 cube_axes_actor.GetYAxesGridlinesProperty().SetColor(color.float_rgb)
2111 cube_axes_actor.GetZAxesGridlinesProperty().SetColor(color.float_rgb)
2112
2113 if isinstance(location, str):
2114 location = location.lower()
2115 if location in ('all'):
2116 cube_axes_actor.SetFlyModeToStaticEdges()
2117 elif location in ('origin'):
2118 cube_axes_actor.SetFlyModeToStaticTriad()
2119 elif location in ('outer'):
2120 cube_axes_actor.SetFlyModeToOuterEdges()
2121 elif location in ('default', 'closest', 'front'):
2122 cube_axes_actor.SetFlyModeToClosestTriad()
2123 elif location in ('furthest', 'back'):
2124 cube_axes_actor.SetFlyModeToFurthestTriad()
2125 else:
2126 msg = (
2127 f'Value of location ("{location}") should be either "all", "origin",'
2128 ' "outer", "default", "closest", "front", "furthest", or "back".'
2129 )
2130 raise ValueError(msg)
2131 elif location is not None:
2132 msg = 'location must be a string'
2133 raise TypeError(msg)
2134
2135 if isinstance(padding, (int, float)) and 0.0 <= padding < 1.0:
2136 if not np.any(np.abs(bounds) == np.inf):
2137 cushion = (
2138 np.array(
2139 [
2140 np.abs(bounds[1] - bounds[0]),
2141 np.abs(bounds[3] - bounds[2]),
2142 np.abs(bounds[5] - bounds[4]),
2143 ],
2144 )
2145 * padding
2146 )
2147 bounds[::2] -= cushion
2148 bounds[1::2] += cushion
2149 else:
2150 msg = f'padding ({padding}) not understood. Must be float between 0 and 1'
2151 raise ValueError(msg)
2152 cube_axes_actor.bounds = bounds
2153
2154 # set axes ranges if input
2155 if axes_ranges is not None:
2156 if isinstance(axes_ranges, (Sequence, np.ndarray)):
2157 axes_ranges = np.asanyarray(axes_ranges)
2158 else:
2159 msg = 'Input axes_ranges must be a numeric sequence.'
2160 raise TypeError(msg)
2161
2162 if not np.issubdtype(axes_ranges.dtype, np.number):
2163 msg = 'All of the elements of axes_ranges must be numbers.'
2164 raise TypeError(msg)
2165
2166 # set the axes ranges
2167 if axes_ranges.shape != (6,):
2168 msg = (
2169 '`axes_ranges` must be passed as a '
2170 '(x_min, x_max, y_min, y_max, z_min, z_max) sequence.'
2171 )
2172 raise ValueError(msg)
2173
2174 cube_axes_actor.x_axis_range = axes_ranges[0], axes_ranges[1]
2175 cube_axes_actor.y_axis_range = axes_ranges[2], axes_ranges[3]
2176 cube_axes_actor.z_axis_range = axes_ranges[4], axes_ranges[5]
2177
2178 # set color
2179 cube_axes_actor.GetXAxesLinesProperty().SetColor(color.float_rgb)
2180 cube_axes_actor.GetYAxesLinesProperty().SetColor(color.float_rgb)
2181 cube_axes_actor.GetZAxesLinesProperty().SetColor(color.float_rgb)
2182
2183 # set font
2184 font_family = parse_font_family(font_family)
2185
2186 if not use_3d_text or not np.allclose(self.scale, [1.0, 1.0, 1.0]):
2187 use_3d_text = False
2188 cube_axes_actor.SetUseTextActor3D(False)
2189 else:
2190 cube_axes_actor.SetUseTextActor3D(True)
2191
2192 props = [
2193 cube_axes_actor.GetTitleTextProperty(0),
2194 cube_axes_actor.GetTitleTextProperty(1),
2195 cube_axes_actor.GetTitleTextProperty(2),
2196 cube_axes_actor.GetLabelTextProperty(0),
2197 cube_axes_actor.GetLabelTextProperty(1),
2198 cube_axes_actor.GetLabelTextProperty(2),
2199 ]
2200
2201 # For 3D text, use `SetFontSize` to a relatively high value and use `SetScreenSize` to
2202 # shrink it back down. This creates a higher-resolution font and makes it appear sharper.
2203 # In VTK 9.6+, the 3D font size is also tied to the value set by SetFontSize, so we need
2204 # an additional scaling factor.
2205 default_screen_size = 10.0
2206 default_font_size = 12
2207 scaled_font_size = 50
2208
2209 for prop in props:
2210 prop.SetColor(color.float_rgb)
2211 prop.SetFontFamily(font_family)
2212 prop.SetBold(bold)
2213
2214 if use_3d_text:
2215 # this merely makes the font sharper
2216 prop.SetFontSize(scaled_font_size)
2217 else:
2218 prop.SetFontSize(font_size)
2219
2220 if use_3d_text:
2221 font_size_factor = 1.0 if vtk_less_than_96 else scaled_font_size / default_font_size
2222 cube_axes_actor.SetScreenSize(
2223 font_size / default_font_size / font_size_factor * default_screen_size
2224 )
2225 elif vtk_less_than_96:
2226 cube_axes_actor.SetScreenSize(font_size / default_font_size * default_screen_size)
2227
2228 if all_edges:
2229 self.add_bounding_box(color=color, corner_factor=corner_factor)
2230
2231 self.add_actor(cube_axes_actor, reset_camera=False, pickable=False, render=render)
2232 self.cube_axes_actor = cube_axes_actor
2233
2234 self.Modified()
2235 return cube_axes_actor
2236
2237 def show_grid(self, **kwargs):
2238 """Show grid lines and bounds axes labels.
2239
2240 A wrapped implementation of :func:`show_bounds()
2241 <pyvista.Renderer.show_bounds>` to change default behavior to use
2242 grid lines and showing the axes labels on the outer edges.
2243
2244 This is intended to be similar to :func:`matplotlib.pyplot.grid`.
2245
2246 Parameters
2247 ----------
2248 **kwargs : dict, optional
2249 See :func:`Renderer.show_bounds` for additional keyword
2250 arguments.
2251
2252 Returns
2253 -------
2254 pyvista.CubeAxesActor
2255 Bounds actor.
2256
2257 See Also
2258 --------
2259 show_bounds
2260 remove_bounds_axes
2261 update_bounds_axes
2262
2263 :ref:`axes_objects_example`
2264 Example showing different axes objects.
2265 :ref:`bounds_example`
2266 Additional examples using this method.
2267
2268 Examples
2269 --------
2270 >>> import pyvista as pv
2271 >>> mesh = pv.Cone()
2272 >>> pl = pv.Plotter()
2273 >>> _ = pl.add_mesh(mesh)
2274 >>> _ = pl.show_grid()
2275 >>> pl.show()
2276
2277 """
2278 kwargs.setdefault('grid', 'back')
2279 kwargs.setdefault('location', 'outer')
2280 kwargs.setdefault('ticks', 'both')
2281 return self.show_bounds(**kwargs)
2282
2283 @_deprecate_positional_args
2284 def remove_bounding_box(self, render=True) -> None: # noqa: FBT002
2285 """Remove bounding box.
2286
2287 Parameters
2288 ----------
2289 render : bool, default: True
2290 Trigger a render once the bounding box is removed.
2291
2292 Examples
2293 --------
2294 >>> import pyvista as pv
2295 >>> pl = pv.Plotter()
2296 >>> _ = pl.add_bounding_box()
2297 >>> pl.remove_bounding_box()
2298
2299 """
2300 if self._box_object is not None:
2301 actor = self.bounding_box_actor
2302 self.bounding_box_actor = None
2303 self._box_object = None
2304 self.remove_actor(actor, reset_camera=False, render=render)
2305 self.Modified()
2306
2307 @_deprecate_positional_args
2308 def add_bounding_box( # noqa: PLR0917
2309 self,
2310 color='grey',
2311 corner_factor=0.5,
2312 line_width=None,
2313 opacity=1.0,
2314 render_lines_as_tubes=False, # noqa: FBT002
2315 lighting=None,
2316 reset_camera=None,
2317 outline=True, # noqa: FBT002
2318 culling='front',
2319 ):
2320 """Add an unlabeled and unticked box at the boundaries of plot.
2321
2322 Useful for when wanting to plot outer grids while still
2323 retaining all edges of the boundary.
2324
2325 Parameters
2326 ----------
2327 color : ColorLike, default: "grey"
2328 Color of all labels and axis titles. Default white.
2329 Either a string, rgb sequence, or hex color string. For
2330 example:
2331
2332 * ``color='white'``
2333 * ``color='w'``
2334 * ``color=[1.0, 1.0, 1.0]``
2335 * ``color='#FFFFFF'``
2336
2337 corner_factor : float, default: 0.5
2338 This is the factor along each axis to draw the default
2339 box. Default is 0.5 to show the full box.
2340
2341 line_width : float, optional
2342 Thickness of lines.
2343
2344 opacity : float, default: 1.0
2345 Opacity of mesh. Should be between 0 and 1.
2346
2347 render_lines_as_tubes : bool, default: False
2348 Show lines as thick tubes rather than flat lines. Control
2349 the width with ``line_width``.
2350
2351 lighting : bool, optional
2352 Enable or disable directional lighting for this actor.
2353
2354 reset_camera : bool, optional
2355 Reset camera position when ``True`` to include all actors.
2356
2357 outline : bool, default: True
2358 Default is ``True``. when ``False``, a box with faces is
2359 shown with the specified culling.
2360
2361 culling : str, default: "front"
2362 Does not render faces on the bounding box that are culled. Options
2363 are ``'front'`` or ``'back'``.
2364
2365 Returns
2366 -------
2367 :vtk:`vtkActor`
2368 VTK actor of the bounding box.
2369
2370 See Also
2371 --------
2372 pyvista.DataSetFilters.bounding_box
2373 Create a bounding box or oriented bounding box for a dataset.
2374
2375 Examples
2376 --------
2377 >>> import pyvista as pv
2378 >>> pl = pv.Plotter()
2379 >>> _ = pl.add_mesh(pv.Sphere())
2380 >>> _ = pl.add_bounding_box(line_width=5, color='black')
2381 >>> pl.show()
2382
2383 """
2384 if lighting is None:
2385 lighting = self._theme.lighting
2386
2387 self.remove_bounding_box()
2388 box: _vtk.vtkOutlineCornerSource | _vtk.vtkCubeSource
2389 if outline:
2390 source = _vtk.vtkOutlineCornerSource()
2391 source.SetCornerFactor(corner_factor)
2392 box = source
2393 else:
2394 box = _vtk.vtkCubeSource()
2395 box.SetBounds(self.bounds)
2396 box.Update()
2397 box_object = wrap(box.GetOutput())
2398 self._bounding_box = box
2399 self._box_object = box_object
2400 name = f'BoundingBox({hex(id(box_object))})'
2401
2402 mapper = _vtk.vtkDataSetMapper()
2403 mapper.SetInputData(box_object)
2404 self.bounding_box_actor, prop = self.add_actor(
2405 mapper,
2406 reset_camera=reset_camera,
2407 name=name,
2408 culling=culling,
2409 pickable=False,
2410 )
2411
2412 prop.SetColor(Color(color, default_color=self._theme.outline_color).float_rgb)
2413 prop.SetOpacity(opacity)
2414 if render_lines_as_tubes:
2415 prop.SetRenderLinesAsTubes(render_lines_as_tubes)
2416
2417 # lighting display style
2418 if lighting is False:
2419 prop.LightingOff()
2420
2421 # set line thickness
2422 if line_width:
2423 prop.SetLineWidth(line_width)
2424
2425 prop.SetRepresentationToSurface()
2426 self.Modified()
2427 return self.bounding_box_actor
2428
2429 @_deprecate_positional_args(allowed=['face'])
2430 def add_floor( # noqa: PLR0917
2431 self,
2432 face='-z',
2433 i_resolution=10,
2434 j_resolution=10,
2435 color=None,
2436 line_width=None,
2437 opacity=1.0,
2438 show_edges=False, # noqa: FBT002
2439 lighting=False, # noqa: FBT002
2440 edge_color=None,
2441 reset_camera=None,
2442 pad=0.0,
2443 offset=0.0,
2444 pickable=False, # noqa: FBT002
2445 store_floor_kwargs=True, # noqa: FBT002
2446 ):
2447 """Show a floor mesh.
2448
2449 This generates planes at the boundaries of the scene to behave
2450 like floors or walls.
2451
2452 Parameters
2453 ----------
2454 face : str, default: "-z"
2455 The face at which to place the plane. Options are
2456 (``'-z'``, ``'-y'``, ``'-x'``, ``'+z'``, ``'+y'``, and
2457 ``'+z'``). Where the ``-/+`` sign indicates on which side of
2458 the axis the plane will lie. For example, ``'-z'`` would
2459 generate a floor on the XY-plane and the bottom of the
2460 scene (minimum z).
2461
2462 i_resolution : int, default: 10
2463 Number of points on the plane in the i direction.
2464
2465 j_resolution : int, default: 10
2466 Number of points on the plane in the j direction.
2467
2468 color : ColorLike, optional
2469 Color of all labels and axis titles. Default gray.
2470 Either a string, rgb list, or hex color string.
2471
2472 line_width : int, optional
2473 Thickness of the edges. Only if ``show_edges`` is
2474 ``True``.
2475
2476 opacity : float, default: 1.0
2477 The opacity of the generated surface.
2478
2479 show_edges : bool, default: False
2480 Flag on whether to show the mesh edges for tiling.
2481
2482 line_width : float, default: False
2483 Thickness of lines. Only valid for wireframe and surface
2484 representations.
2485
2486 lighting : bool, default: False
2487 Enable or disable view direction lighting.
2488
2489 edge_color : ColorLike, optional
2490 Color of the edges of the mesh.
2491
2492 reset_camera : bool, optional
2493 Resets the camera when ``True`` after adding the floor.
2494
2495 pad : float, default: 0.0
2496 Percentage padding between 0 and 1.
2497
2498 offset : float, default: 0.0
2499 Percentage offset along plane normal.
2500
2501 pickable : bool, default: False
2502 Make this floor actor pickable in the renderer.
2503
2504 store_floor_kwargs : bool, default: True
2505 Stores the keyword arguments used when adding this floor.
2506 Useful when updating the bounds and regenerating the
2507 floor.
2508
2509 Returns
2510 -------
2511 :vtk:`vtkActor`
2512 VTK actor of the floor.
2513
2514 Examples
2515 --------
2516 Add a floor below a sphere and plot it.
2517
2518 >>> import pyvista as pv
2519 >>> pl = pv.Plotter()
2520 >>> actor = pl.add_mesh(pv.Sphere())
2521 >>> actor = pl.add_floor()
2522 >>> pl.show()
2523
2524 """
2525 if store_floor_kwargs:
2526 kwargs = locals()
2527 kwargs.pop('self')
2528 self._floor_kwargs.append(kwargs)
2529 ranges = np.ptp(np.array(self.bounds).reshape(-1, 2), axis=1)
2530 ranges += ranges * pad
2531 center = np.array(self.center)
2532 if face.lower() in '-z':
2533 center[2] = self.bounds.z_min - (ranges[2] * offset)
2534 normal = (0, 0, 1)
2535 i_size = ranges[0]
2536 j_size = ranges[1]
2537 elif face.lower() in '-y':
2538 center[1] = self.bounds.y_min - (ranges[1] * offset)
2539 normal = (0, 1, 0)
2540 i_size = ranges[2]
2541 j_size = ranges[0]
2542 elif face.lower() in '-x':
2543 center[0] = self.bounds.x_min - (ranges[0] * offset)
2544 normal = (1, 0, 0)
2545 i_size = ranges[2]
2546 j_size = ranges[1]
2547 elif face.lower() in '+z':
2548 center[2] = self.bounds.z_max + (ranges[2] * offset)
2549 normal = (0, 0, -1)
2550 i_size = ranges[0]
2551 j_size = ranges[1]
2552 elif face.lower() in '+y':
2553 center[1] = self.bounds.y_max + (ranges[1] * offset)
2554 normal = (0, -1, 0)
2555 i_size = ranges[2]
2556 j_size = ranges[0]
2557 elif face.lower() in '+x':
2558 center[0] = self.bounds.x_max + (ranges[0] * offset)
2559 normal = (-1, 0, 0)
2560 i_size = ranges[2]
2561 j_size = ranges[1]
2562 else:
2563 msg = f'Face ({face}) not implemented'
2564 raise NotImplementedError(msg)
2565 floor = pv.Plane(
2566 center=center,
2567 direction=normal,
2568 i_size=i_size,
2569 j_size=j_size,
2570 i_resolution=i_resolution,
2571 j_resolution=j_resolution,
2572 )
2573 floor.clear_data()
2574 self._floor = floor
2575
2576 if lighting is None:
2577 lighting = self._theme.lighting
2578
2579 self.remove_bounding_box()
2580 mapper = DataSetMapper()
2581 mapper.SetInputData(self._floor)
2582 actor, prop = self.add_actor(
2583 mapper,
2584 reset_camera=reset_camera,
2585 name=f'Floor({face})',
2586 pickable=pickable,
2587 )
2588
2589 prop.SetColor(Color(color, default_color=self._theme.floor_color).float_rgb)
2590 prop.SetOpacity(opacity)
2591
2592 # edge display style
2593 if show_edges:
2594 prop.EdgeVisibilityOn()
2595 prop.SetEdgeColor(Color(edge_color, default_color=self._theme.edge_color).float_rgb)
2596
2597 # lighting display style
2598 if lighting is False:
2599 prop.LightingOff()
2600
2601 # set line thickness
2602 if line_width:
2603 prop.SetLineWidth(line_width)
2604
2605 prop.SetRepresentationToSurface()
2606 self._floors.append(actor)
2607 return actor
2608
2609 @_deprecate_positional_args
2610 def remove_floors(self, clear_kwargs=True, render=True) -> None: # noqa: FBT002
2611 """Remove all floor actors.
2612
2613 Parameters
2614 ----------
2615 clear_kwargs : bool, default: True
2616 Clear default floor arguments.
2617
2618 render : bool, default: True
2619 Render upon removing the floor.
2620
2621 Examples
2622 --------
2623 Add a floor below a sphere, remove it, and then plot it.
2624
2625 >>> import pyvista as pv
2626 >>> pl = pv.Plotter()
2627 >>> actor = pl.add_mesh(pv.Sphere())
2628 >>> actor = pl.add_floor()
2629 >>> pl.remove_floors()
2630 >>> pl.show()
2631
2632 """
2633 if hasattr(self, '_floor') and self._floor is not None:
2634 self._floor.ReleaseData()
2635 self._floor = None
2636 for actor in self._floors:
2637 self.remove_actor(actor, reset_camera=False, render=render)
2638 self._floors.clear()
2639 if clear_kwargs:
2640 self._floor_kwargs.clear()
2641
2642 def remove_bounds_axes(self) -> None:
2643 """Remove bounds axes.
2644
2645 Examples
2646 --------
2647 >>> import pyvista as pv
2648 >>> pl = pv.Plotter(shape=(1, 2))
2649 >>> pl.subplot(0, 0)
2650 >>> actor = pl.add_mesh(pv.Sphere())
2651 >>> actor = pl.show_bounds(grid='front', location='outer')
2652 >>> pl.subplot(0, 1)
2653 >>> actor = pl.add_mesh(pv.Sphere())
2654 >>> actor = pl.show_bounds(grid='front', location='outer')
2655 >>> actor = pl.remove_bounds_axes()
2656 >>> pl.show()
2657
2658 """
2659 if self.cube_axes_actor is not None:
2660 self.remove_actor(self.cube_axes_actor)
2661 self.cube_axes_actor = None
2662 self.Modified()
2663
2664 def add_light(self, light):
2665 """Add a light to the renderer.
2666
2667 Parameters
2668 ----------
2669 light : :vtk:`vtkLight` | Light
2670 Light to add.
2671
2672 """
2673 # convert from a vtk type if applicable
2674 if isinstance(light, _vtk.vtkLight) and not isinstance(light, pv.Light):
2675 light = pv.Light.from_vtk(light)
2676
2677 if not isinstance(light, pv.Light):
2678 msg = f'Expected Light instance, got {type(light).__name__} instead.'
2679 raise TypeError(msg)
2680 self._lights.append(light)
2681 self.AddLight(light)
2682 self.Modified()
2683
2684 # we add the renderer to add/remove the light actor if
2685 # positional or cone angle is modified
2686 light.add_renderer(self)
2687
2688 @property
2689 def lights(self): # numpydoc ignore=RT01
2690 """Return a list of all lights in the renderer.
2691
2692 Returns
2693 -------
2694 list
2695 Lights in the renderer.
2696
2697 Examples
2698 --------
2699 >>> import pyvista as pv
2700 >>> pl = pv.Plotter()
2701 >>> pl.renderer.lights # doctest:+SKIP
2702 [<Light (Headlight) at ...>,
2703 <Light (Camera Light) at 0x7f1dd8155760>,
2704 <Light (Camera Light) at 0x7f1dd8155340>,
2705 <Light (Camera Light) at 0x7f1dd8155460>,
2706 <Light (Camera Light) at 0x7f1dd8155f40>]
2707
2708 """
2709 return list(self.GetLights()) # type: ignore[call-overload]
2710
2711 def remove_all_lights(self) -> None:
2712 """Remove all lights from the renderer."""
2713 self.RemoveAllLights()
2714 self._lights.clear()
2715
2716 def clear_actors(self) -> None:
2717 """Remove all actors (keep lights and properties)."""
2718 if self._actors:
2719 for actor in list(self._actors):
2720 with contextlib.suppress(KeyError):
2721 self.remove_actor(actor, reset_camera=False, render=False)
2722 self.Modified()
2723
2724 def clear(self) -> None:
2725 """Remove all actors and properties.
2726
2727 See Also
2728 --------
2729 :ref:`clear_example`
2730
2731 """
2732 self.clear_actors()
2733 if self._charts is not None:
2734 self._charts.deep_clean()
2735 self.remove_all_lights()
2736 self.RemoveAllViewProps()
2737 self.Modified()
2738
2739 self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
2740 self._scalar_bar_slot_lookup = {}
2741
2742 def set_focus(self, point) -> None:
2743 """Set focus to a point.
2744
2745 Parameters
2746 ----------
2747 point : sequence[float]
2748 Cartesian point to focus on in the form of ``[x, y, z]``.
2749
2750 Examples
2751 --------
2752 >>> import pyvista as pv
2753 >>> mesh = pv.Cube()
2754 >>> pl = pv.Plotter()
2755 >>> _ = pl.add_mesh(mesh, show_edges=True)
2756 >>> _ = pl.add_point_labels([mesh.points[1]], ['Focus'])
2757 >>> _ = pl.camera # this initializes the camera
2758 >>> pl.set_focus(mesh.points[1])
2759 >>> pl.show()
2760
2761 """
2762 if isinstance(point, np.ndarray) and point.ndim != 1:
2763 point = point.ravel()
2764 self.camera.focal_point = scale_point(self.camera, point, invert=False)
2765 self.camera_set = True
2766 self.Modified()
2767
2768 @_deprecate_positional_args(allowed=['point'])
2769 def set_position(self, point, reset=False, render=True) -> None: # noqa: FBT002
2770 """Set camera position to a point.
2771
2772 Parameters
2773 ----------
2774 point : sequence
2775 Cartesian point to focus on in the form of ``[x, y, z]``.
2776
2777 reset : bool, default: False
2778 Whether to reset the camera after setting the camera
2779 position.
2780
2781 render : bool, default: True
2782 If the render window is being shown, trigger a render
2783 after setting the position.
2784
2785 Examples
2786 --------
2787 Move the camera far away to ``[7, 7, 7]``.
2788
2789 >>> import pyvista as pv
2790 >>> mesh = pv.Cube()
2791 >>> pl = pv.Plotter()
2792 >>> _ = pl.add_mesh(mesh, show_edges=True)
2793 >>> pl.set_position([7, 7, 7])
2794 >>> pl.show()
2795
2796 """
2797 if isinstance(point, np.ndarray) and point.ndim != 1:
2798 point = point.ravel()
2799 self.camera.position = scale_point(self.camera, point, invert=False)
2800 if reset:
2801 self.reset_camera(render=render)
2802 self.camera_set = True
2803 self.Modified()
2804
2805 @_deprecate_positional_args(allowed=['vector'])
2806 def set_viewup(self, vector, reset=True, render=True) -> None: # noqa: FBT002
2807 """Set camera viewup vector.
2808
2809 Parameters
2810 ----------
2811 vector : sequence[float]
2812 New camera viewup vector.
2813
2814 reset : bool, default: True
2815 Whether to reset the camera after setting the camera
2816 position.
2817
2818 render : bool, default: True
2819 If the render window is being shown, trigger a render
2820 after setting the viewup.
2821
2822 Examples
2823 --------
2824 Look from the top down by setting view up to ``[0, 1, 0]``.
2825 Notice how the y-axis appears vertical.
2826
2827 >>> from pyvista import demos
2828 >>> pl = demos.orientation_plotter()
2829 >>> pl.set_viewup([0, 1, 0])
2830 >>> pl.show()
2831
2832 """
2833 if isinstance(vector, np.ndarray) and vector.ndim != 1:
2834 vector = vector.ravel()
2835
2836 self.camera.up = vector
2837 if reset:
2838 self.reset_camera(render=render)
2839
2840 self.camera_set = True
2841 self.Modified()
2842
2843 def enable_parallel_projection(self) -> None:
2844 """Enable parallel projection.
2845
2846 The camera will have a parallel projection. Parallel projection is
2847 often useful when viewing images or 2D datasets.
2848
2849 See Also
2850 --------
2851 pyvista.Plotter.enable_2d_style
2852
2853 Examples
2854 --------
2855 >>> import pyvista as pv
2856 >>> from pyvista import demos
2857 >>> pl = pv.demos.orientation_plotter()
2858 >>> pl.enable_parallel_projection()
2859 >>> pl.show()
2860
2861 """
2862 # Fix the 'reset camera' effect produced by the VTK when parallel
2863 # projection is enabled.
2864 angle = np.radians(self.camera.view_angle)
2865 self.camera.parallel_scale = self.camera.distance * np.sin(0.5 * angle)
2866
2867 self.camera.enable_parallel_projection()
2868 self.Modified()
2869
2870 def disable_parallel_projection(self) -> None:
2871 """Reset the camera to use perspective projection.
2872
2873 Examples
2874 --------
2875 >>> import pyvista as pv
2876 >>> from pyvista import demos
2877 >>> pl = pv.demos.orientation_plotter()
2878 >>> pl.disable_parallel_projection()
2879 >>> pl.show()
2880
2881 """
2882 # Fix the 'reset camera' effect produced by the VTK when parallel
2883 # projection is disabled.
2884 focus = self.camera.focal_point
2885 angle = np.radians(self.camera.view_angle)
2886 distance = self.camera.parallel_scale / np.sin(0.5 * angle)
2887 direction = self.camera.direction
2888 x = focus[0] - distance * direction[0]
2889 y = focus[1] - distance * direction[1]
2890 z = focus[2] - distance * direction[2]
2891 self.camera.position = (x, y, z)
2892 self.ResetCameraClippingRange()
2893
2894 self.camera.disable_parallel_projection()
2895 self.Modified()
2896
2897 @property
2898 def parallel_projection(self): # numpydoc ignore=RT01
2899 """Return parallel projection state of active render window.
2900
2901 Examples
2902 --------
2903 >>> import pyvista as pv
2904 >>> pl = pv.Plotter()
2905 >>> pl.parallel_projection = False
2906 >>> pl.parallel_projection
2907 False
2908
2909 """
2910 return self.camera.parallel_projection
2911
2912 @parallel_projection.setter
2913 def parallel_projection(self, state) -> None:
2914 self.camera.parallel_projection = state
2915 self.Modified()
2916
2917 @property
2918 def parallel_scale(self): # numpydoc ignore=RT01
2919 """Return parallel scale of active render window.
2920
2921 Examples
2922 --------
2923 >>> import pyvista as pv
2924 >>> pl = pv.Plotter()
2925 >>> pl.parallel_scale = 2
2926
2927 """
2928 return self.camera.parallel_scale
2929
2930 @parallel_scale.setter
2931 def parallel_scale(self, value) -> None:
2932 self.camera.parallel_scale = value
2933 self.Modified()
2934
2935 @_deprecate_positional_args(allowed=['actor'])
2936 def remove_actor(self, actor, reset_camera=False, render=True): # noqa: FBT002
2937 """Remove an actor from the Renderer.
2938
2939 Parameters
2940 ----------
2941 actor : str | :vtk:`vtkActor` | list | tuple
2942 If the type is ``str``, removes the previously added actor
2943 with the given name. If the type is :vtk:`vtkActor`,
2944 removes the actor if it's previously added to the
2945 Renderer. If ``list`` or ``tuple``, removes iteratively
2946 each actor.
2947
2948 reset_camera : bool, optional
2949 Resets camera so all actors can be seen.
2950
2951 render : bool, optional
2952 Render upon actor removal. Set this to ``False`` to stop
2953 the render window from rendering when an actor is removed.
2954
2955 Returns
2956 -------
2957 bool
2958 ``True`` when actor removed. ``False`` when actor has not
2959 been removed.
2960
2961 Examples
2962 --------
2963 Add two meshes to a plotter and then remove the sphere actor.
2964
2965 >>> import pyvista as pv
2966 >>> mesh = pv.Cube()
2967 >>> pl = pv.Plotter()
2968 >>> cube_actor = pl.add_mesh(pv.Cube(), show_edges=True)
2969 >>> sphere_actor = pl.add_mesh(pv.Sphere(), show_edges=True)
2970 >>> _ = pl.remove_actor(cube_actor)
2971 >>> pl.show()
2972
2973 """
2974 if isinstance(actor, str):
2975 name = actor
2976 keys = list(self._actors.keys())
2977 names = [k for k in keys if k.startswith(f'{name}-')]
2978 if len(names) > 0:
2979 self.remove_actor(names, reset_camera=reset_camera, render=render)
2980 try:
2981 actor = self._actors[name]
2982 except KeyError:
2983 # If actor of that name is not present then return success
2984 return False
2985 if isinstance(actor, Iterable):
2986 success = False
2987 for a in actor:
2988 rv = self.remove_actor(a, reset_camera=reset_camera, render=render)
2989 if rv or success:
2990 success = True
2991 return success
2992 if actor is None:
2993 return False
2994
2995 # remove any labels associated with the actor
2996 self._labels.pop(actor.GetAddressAsString(''), None)
2997
2998 # ensure any scalar bars associated with this actor are removed
2999 with contextlib.suppress(AttributeError, ReferenceError):
3000 self.parent.scalar_bars._remove_mapper_from_plotter(actor)
3001 self.RemoveActor(actor)
3002 self.update_bounds_axes()
3003 if reset_camera or (not self.camera_set and reset_camera is None):
3004 self.reset_camera(render=render)
3005 elif render:
3006 self.parent.render()
3007
3008 self.Modified()
3009 return True
3010
3011 @_deprecate_positional_args(allowed=['xscale', 'yscale', 'zscale'])
3012 def set_scale( # noqa: PLR0917
3013 self,
3014 xscale=None,
3015 yscale=None,
3016 zscale=None,
3017 reset_camera=True, # noqa: FBT002
3018 render=True, # noqa: FBT002
3019 ) -> None:
3020 """Scale all the actors in the scene.
3021
3022 Scaling in performed independently on the X, Y and z-axis.
3023 A scale of zero is illegal and will be replaced with one.
3024
3025 .. warning::
3026 Setting the scale on the renderer is a convenience method to
3027 individually scale each of the actors in the scene. If a scale
3028 was set on an actor previously, it will be reset to the scale
3029 of this Renderer.
3030
3031 Parameters
3032 ----------
3033 xscale : float, optional
3034 Scaling in the x direction. Default is ``None``, which
3035 does not change existing scaling.
3036
3037 yscale : float, optional
3038 Scaling in the y direction. Default is ``None``, which
3039 does not change existing scaling.
3040
3041 zscale : float, optional
3042 Scaling in the z direction. Default is ``None``, which
3043 does not change existing scaling.
3044
3045 reset_camera : bool, default: True
3046 Resets camera so all actors can be seen.
3047
3048 render : bool, default: True
3049 If the render window is being shown, trigger a render
3050 after setting the scale.
3051
3052 Examples
3053 --------
3054 Set the scale in the z direction to be 2 times that of
3055 nominal. Leave the other axes unscaled.
3056
3057 >>> import pyvista as pv
3058 >>> pl = pv.Plotter()
3059 >>> pl.set_scale(zscale=2)
3060 >>> _ = pl.add_mesh(pv.Sphere()) # perfect sphere
3061 >>> pl.show()
3062
3063 """
3064 if xscale is None:
3065 xscale = self.scale[0]
3066 if yscale is None:
3067 yscale = self.scale[1]
3068 if zscale is None:
3069 zscale = self.scale[2]
3070 self.scale = [xscale, yscale, zscale]
3071
3072 # Reset all actors to match this scale
3073 for actor in self.actors.values():
3074 if hasattr(actor, 'SetScale'):
3075 actor.SetScale(self.scale)
3076
3077 self.parent.render()
3078 if reset_camera:
3079 self.update_bounds_axes()
3080 self.reset_camera(render=render)
3081 self.Modified()
3082
3083 @_deprecate_positional_args
3084 def get_default_cam_pos(self, negative=False): # noqa: FBT002
3085 """Return the default focal points and viewup.
3086
3087 Uses ResetCamera to make a useful view.
3088
3089 Parameters
3090 ----------
3091 negative : bool, default: False
3092 View from the opposite direction.
3093
3094 Returns
3095 -------
3096 list
3097 List of camera position:
3098
3099 * Position
3100 * Focal point
3101 * View up
3102
3103 """
3104 focal_pt = self.center
3105 if any(np.isnan(focal_pt)):
3106 focal_pt = (0.0, 0.0, 0.0)
3107 position = np.array(self._theme.camera.position).astype(float)
3108 if negative:
3109 position *= -1
3110 position = position / np.array(self.scale).astype(float)
3111 return [position + np.array(focal_pt), focal_pt, self._theme.camera.viewup]
3112
3113 def update_bounds_axes(self) -> None:
3114 """Update the bounds axes of the render window."""
3115 if self._box_object is not None and self.bounding_box_actor is not None:
3116 if not np.allclose(self._box_object.bounds, self.bounds):
3117 color = self.bounding_box_actor.GetProperty().GetColor()
3118 self.remove_bounding_box()
3119 self.add_bounding_box(color=color)
3120 self.remove_floors(clear_kwargs=False)
3121 for floor_kwargs in self._floor_kwargs:
3122 floor_kwargs['store_floor_kwargs'] = False
3123 self.add_floor(**floor_kwargs)
3124 if self.cube_axes_actor is not None:
3125 self.cube_axes_actor.update_bounds(self.bounds)
3126 if not np.allclose(self.scale, [1.0, 1.0, 1.0]):
3127 self.cube_axes_actor.SetUse2DMode(True)
3128 else:
3129 self.cube_axes_actor.SetUse2DMode(False)
3130 self.Modified()
3131
3132 @_deprecate_positional_args
3133 def reset_camera(self, render=True, bounds=None) -> None: # noqa: FBT002
3134 """Reset the camera of the active render window.
3135
3136 The camera slides along the vector defined from camera
3137 position to focal point until all of the actors can be seen.
3138
3139 Parameters
3140 ----------
3141 render : bool, default: True
3142 Trigger a render after resetting the camera.
3143
3144 bounds : iterable(int), optional
3145 Automatically set up the camera based on a specified bounding box
3146 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3147
3148 Examples
3149 --------
3150 Add a mesh and place the camera position too close to the
3151 mesh. Then reset the camera and show the mesh.
3152
3153 >>> import pyvista as pv
3154 >>> pl = pv.Plotter()
3155 >>> actor = pl.add_mesh(pv.Sphere(), show_edges=True)
3156 >>> pl.set_position((0, 0.1, 0.1))
3157 >>> pl.reset_camera()
3158 >>> pl.show()
3159
3160 """
3161 if bounds is not None:
3162 self.ResetCamera(*bounds)
3163 else:
3164 self.ResetCamera()
3165
3166 self.reset_camera_clipping_range()
3167
3168 if render:
3169 self.parent.render()
3170 self.Modified()
3171
3172 def isometric_view(self) -> None:
3173 """Reset the camera to a default isometric view.
3174
3175 DEPRECATED: Please use ``view_isometric``.
3176
3177 """
3178 self.view_isometric()
3179
3180 @_deprecate_positional_args
3181 def view_isometric(self, negative=False, render=True, bounds=None) -> None: # noqa: FBT002
3182 """Reset the camera to a default isometric view.
3183
3184 The view will show all the actors in the scene.
3185
3186 Parameters
3187 ----------
3188 negative : bool, default: False
3189 View from the other isometric direction.
3190
3191 render : bool, default: True
3192 If the render window is being shown, trigger a render
3193 after setting the camera position.
3194
3195 bounds : iterable(int), optional
3196 Automatically set up the camera based on a specified bounding box
3197 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3198
3199 Examples
3200 --------
3201 Isometric view.
3202
3203 >>> from pyvista import demos
3204 >>> pl = demos.orientation_plotter()
3205 >>> pl.view_isometric()
3206 >>> pl.show()
3207
3208 Negative isometric view.
3209
3210 >>> from pyvista import demos
3211 >>> pl = demos.orientation_plotter()
3212 >>> pl.view_isometric(negative=True)
3213 >>> pl.show()
3214
3215 """
3216 position = self.get_default_cam_pos(negative=negative)
3217 self.camera_position = CameraPosition(*position)
3218 self.camera_set = negative
3219 self.reset_camera(render=render, bounds=bounds)
3220
3221 @_deprecate_positional_args(allowed=['vector', 'viewup'])
3222 def view_vector( # noqa: PLR0917
3223 self,
3224 vector,
3225 viewup=None,
3226 render=True, # noqa: FBT002
3227 bounds=None,
3228 ) -> None:
3229 """Point the camera in the direction of the given vector.
3230
3231 Parameters
3232 ----------
3233 vector : sequence[float]
3234 Direction to point the camera in.
3235
3236 viewup : sequence[float], optional
3237 Sequence describing the view up of the camera.
3238
3239 render : bool, default: True
3240 If the render window is being shown, trigger a render
3241 after setting the camera position.
3242
3243 bounds : iterable(int), optional
3244 Automatically set up the camera based on a specified bounding box
3245 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3246
3247 """
3248 focal_pt = self.center
3249 if viewup is None:
3250 viewup = self._theme.camera.viewup
3251 cpos = CameraPosition(vector + np.array(focal_pt), focal_pt, viewup)
3252 self.camera_position = cpos
3253 self.reset_camera(render=render, bounds=bounds)
3254
3255 @_deprecate_positional_args
3256 def view_xy(self, negative=False, render=True, bounds=None) -> None: # noqa: FBT002
3257 """View the XY plane.
3258
3259 Parameters
3260 ----------
3261 negative : bool, default: False
3262 View from the opposite direction.
3263
3264 render : bool, default: True
3265 If the render window is being shown, trigger a render
3266 after setting the camera position.
3267
3268 bounds : iterable(int), optional
3269 Automatically set up the camera based on a specified bounding box
3270 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3271
3272 Examples
3273 --------
3274 View the XY plane of a built-in mesh example.
3275
3276 >>> from pyvista import examples
3277 >>> import pyvista as pv
3278 >>> airplane = examples.load_airplane()
3279 >>> pl = pv.Plotter()
3280 >>> _ = pl.add_mesh(airplane)
3281 >>> pl.view_xy()
3282 >>> pl.show()
3283
3284 """
3285 self.view_vector(*view_vectors('xy', negative=negative), render=render, bounds=bounds)
3286
3287 @_deprecate_positional_args
3288 def view_yx(self, negative=False, render=True, bounds=None) -> None: # noqa: FBT002
3289 """View the YX plane.
3290
3291 Parameters
3292 ----------
3293 negative : bool, default: False
3294 View from the opposite direction.
3295
3296 render : bool, default: True
3297 If the render window is being shown, trigger a render
3298 after setting the camera position.
3299
3300 bounds : iterable(int), optional
3301 Automatically set up the camera based on a specified bounding box
3302 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3303
3304 Examples
3305 --------
3306 View the YX plane of a built-in mesh example.
3307
3308 >>> from pyvista import examples
3309 >>> import pyvista as pv
3310 >>> airplane = examples.load_airplane()
3311 >>> pl = pv.Plotter()
3312 >>> _ = pl.add_mesh(airplane)
3313 >>> pl.view_yx()
3314 >>> pl.show()
3315
3316 """
3317 self.view_vector(*view_vectors('yx', negative=negative), render=render, bounds=bounds)
3318
3319 @_deprecate_positional_args
3320 def view_xz(self, negative=False, render=True, bounds=None) -> None: # noqa: FBT002
3321 """View the XZ plane.
3322
3323 Parameters
3324 ----------
3325 negative : bool, default: False
3326 View from the opposite direction.
3327
3328 render : bool, default: True
3329 If the render window is being shown, trigger a render
3330 after setting the camera position.
3331
3332 bounds : iterable(int), optional
3333 Automatically set up the camera based on a specified bounding box
3334 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3335
3336 Examples
3337 --------
3338 View the XZ plane of a built-in mesh example.
3339
3340 >>> from pyvista import examples
3341 >>> import pyvista as pv
3342 >>> airplane = examples.load_airplane()
3343 >>> pl = pv.Plotter()
3344 >>> _ = pl.add_mesh(airplane)
3345 >>> pl.view_xz()
3346 >>> pl.show()
3347
3348 """
3349 self.view_vector(*view_vectors('xz', negative=negative), render=render, bounds=bounds)
3350
3351 @_deprecate_positional_args
3352 def view_zx(self, negative=False, render=True, bounds=None) -> None: # noqa: FBT002
3353 """View the ZX plane.
3354
3355 Parameters
3356 ----------
3357 negative : bool, default: False
3358 View from the opposite direction.
3359
3360 render : bool, default: True
3361 If the render window is being shown, trigger a render
3362 after setting the camera position.
3363
3364 bounds : iterable(int), optional
3365 Automatically set up the camera based on a specified bounding box
3366 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3367
3368 Examples
3369 --------
3370 View the ZX plane of a built-in mesh example.
3371
3372 >>> from pyvista import examples
3373 >>> import pyvista as pv
3374 >>> airplane = examples.load_airplane()
3375 >>> pl = pv.Plotter()
3376 >>> _ = pl.add_mesh(airplane)
3377 >>> pl.view_zx()
3378 >>> pl.show()
3379
3380 """
3381 self.view_vector(*view_vectors('zx', negative=negative), render=render, bounds=bounds)
3382
3383 @_deprecate_positional_args
3384 def view_yz(self, negative=False, render=True, bounds=None) -> None: # noqa: FBT002
3385 """View the YZ plane.
3386
3387 Parameters
3388 ----------
3389 negative : bool, default: False
3390 View from the opposite direction.
3391
3392 render : bool, default: True
3393 If the render window is being shown, trigger a render
3394 after setting the camera position.
3395
3396 bounds : iterable(int), optional
3397 Automatically set up the camera based on a specified bounding box
3398 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3399
3400 Examples
3401 --------
3402 View the YZ plane of a built-in mesh example.
3403
3404 >>> from pyvista import examples
3405 >>> import pyvista as pv
3406 >>> airplane = examples.load_airplane()
3407 >>> pl = pv.Plotter()
3408 >>> _ = pl.add_mesh(airplane)
3409 >>> pl.view_yz()
3410 >>> pl.show()
3411
3412 """
3413 self.view_vector(*view_vectors('yz', negative=negative), render=render, bounds=bounds)
3414
3415 @_deprecate_positional_args
3416 def view_zy(self, negative=False, render=True, bounds=None) -> None: # noqa: FBT002
3417 """View the ZY plane.
3418
3419 Parameters
3420 ----------
3421 negative : bool, default: False
3422 View from the opposite direction.
3423
3424 render : bool, default: True
3425 If the render window is being shown, trigger a render
3426 after setting the camera position.
3427
3428 bounds : iterable(int), optional
3429 Automatically set up the camera based on a specified bounding box
3430 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3431
3432 Examples
3433 --------
3434 View the ZY plane of a built-in mesh example.
3435
3436 >>> from pyvista import examples
3437 >>> import pyvista as pv
3438 >>> airplane = examples.load_airplane()
3439 >>> pl = pv.Plotter()
3440 >>> _ = pl.add_mesh(airplane)
3441 >>> pl.view_zy()
3442 >>> pl.show()
3443
3444 """
3445 self.view_vector(*view_vectors('zy', negative=negative), render=render, bounds=bounds)
3446
3447 def disable(self) -> None:
3448 """Disable this renderer's camera from being interactive."""
3449 self.SetInteractive(0)
3450
3451 def enable(self) -> None:
3452 """Enable this renderer's camera to be interactive."""
3453 self.SetInteractive(1)
3454
3455 def add_blurring(self) -> None:
3456 """Add blurring.
3457
3458 This can be added several times to increase the degree of blurring.
3459
3460 Examples
3461 --------
3462 Add two blurring passes to the plotter and show it.
3463
3464 >>> import pyvista as pv
3465 >>> pl = pv.Plotter()
3466 >>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
3467 >>> pl.add_blurring()
3468 >>> pl.add_blurring()
3469 >>> pl.show()
3470
3471 See :ref:`blurring_example` for a full example using this method.
3472
3473 """
3474 self._render_passes.add_blur_pass()
3475
3476 def remove_blurring(self) -> None:
3477 """Remove a single blurring pass.
3478
3479 You will need to run this multiple times to remove all blurring passes.
3480
3481 Examples
3482 --------
3483 >>> import pyvista as pv
3484 >>> pl = pv.Plotter()
3485 >>> _ = pl.add_mesh(pv.Sphere())
3486 >>> pl.add_blurring()
3487 >>> pl.remove_blurring()
3488 >>> pl.show()
3489
3490 """
3491 self._render_passes.remove_blur_pass()
3492
3493 @_deprecate_positional_args
3494 def enable_depth_of_field(self, automatic_focal_distance=True) -> None: # noqa: FBT002
3495 """Enable depth of field plotting.
3496
3497 Parameters
3498 ----------
3499 automatic_focal_distance : bool, default: True
3500 Use automatic focal distance calculation. When enabled, the center
3501 of the viewport will always be in focus regardless of where the
3502 focal point is.
3503
3504 Examples
3505 --------
3506 Create five spheres and demonstrate the effect of depth of field.
3507
3508 >>> import pyvista as pv
3509 >>> from pyvista import examples
3510 >>> pl = pv.Plotter(lighting='three lights')
3511 >>> pl.background_color = 'w'
3512 >>> for i in range(5):
3513 ... mesh = pv.Sphere(center=(-i * 4, 0, 0))
3514 ... color = [0, 255 - i * 20, 30 + i * 50]
3515 ... _ = pl.add_mesh(
3516 ... mesh,
3517 ... show_edges=False,
3518 ... pbr=True,
3519 ... metallic=1.0,
3520 ... color=color,
3521 ... )
3522 >>> pl.camera.zoom(1.8)
3523 >>> pl.camera_position = pv.CameraPosition(
3524 ... position=(4.74, 0.959, 0.525),
3525 ... focal_point=(0.363, 0.3116, 0.132),
3526 ... viewup=(-0.088, -0.0075, 0.996),
3527 ... )
3528 >>> pl.enable_depth_of_field()
3529 >>> pl.show()
3530
3531 See :ref:`depth_of_field_example` for a full example using this method.
3532
3533 """
3534 self._render_passes.enable_depth_of_field_pass(
3535 automatic_focal_distance=automatic_focal_distance
3536 )
3537
3538 def disable_depth_of_field(self) -> None:
3539 """Disable depth of field plotting.
3540
3541 Examples
3542 --------
3543 >>> import pyvista as pv
3544 >>> pl = pv.Plotter(lighting='three lights')
3545 >>> pl.enable_depth_of_field()
3546 >>> pl.disable_depth_of_field()
3547
3548 """
3549 self._render_passes.disable_depth_of_field_pass()
3550
3551 def enable_eye_dome_lighting(self) -> None:
3552 """Enable eye dome lighting (EDL).
3553
3554 Returns
3555 -------
3556 :vtk:`vtkOpenGLRenderer`
3557 VTK renderer with eye dome lighting pass.
3558
3559 Examples
3560 --------
3561 >>> import pyvista as pv
3562 >>> pl = pv.Plotter()
3563 >>> _ = pl.enable_eye_dome_lighting()
3564
3565 """
3566 self._render_passes.enable_edl_pass()
3567
3568 def disable_eye_dome_lighting(self) -> None:
3569 """Disable eye dome lighting (EDL).
3570
3571 Examples
3572 --------
3573 >>> import pyvista as pv
3574 >>> pl = pv.Plotter()
3575 >>> pl.disable_eye_dome_lighting()
3576
3577 """
3578 self._render_passes.disable_edl_pass()
3579
3580 def enable_shadows(self) -> None:
3581 """Enable shadows.
3582
3583 Examples
3584 --------
3585 First, plot without shadows enabled (default)
3586
3587 >>> import pyvista as pv
3588 >>> mesh = pv.Sphere()
3589 >>> pl = pv.Plotter(lighting='none', window_size=(1000, 1000))
3590 >>> light = pv.Light()
3591 >>> light.set_direction_angle(20, -20)
3592 >>> pl.add_light(light)
3593 >>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
3594 >>> _ = pl.add_mesh(pv.Box((-1.2, -1, -1, 1, -1, 1)))
3595 >>> pl.show()
3596
3597 Now, enable shadows.
3598
3599 >>> import pyvista as pv
3600 >>> mesh = pv.Sphere()
3601 >>> pl = pv.Plotter(lighting='none', window_size=(1000, 1000))
3602 >>> light = pv.Light()
3603 >>> light.set_direction_angle(20, -20)
3604 >>> pl.add_light(light)
3605 >>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
3606 >>> _ = pl.add_mesh(pv.Box((-1.2, -1, -1, 1, -1, 1)))
3607 >>> pl.enable_shadows()
3608 >>> pl.show()
3609
3610 """
3611 self._render_passes.enable_shadow_pass()
3612
3613 def disable_shadows(self) -> None:
3614 """Disable shadows.
3615
3616 Examples
3617 --------
3618 >>> import pyvista as pv
3619 >>> pl = pv.Plotter()
3620 >>> pl.disable_shadows()
3621
3622 """
3623 self._render_passes.disable_shadow_pass()
3624
3625 @_deprecate_positional_args
3626 def enable_ssao( # noqa: PLR0917
3627 self,
3628 radius=0.5,
3629 bias=0.005,
3630 kernel_size=256,
3631 blur=True, # noqa: FBT002
3632 ) -> None:
3633 """Enable surface space ambient occlusion (SSAO).
3634
3635 SSAO can approximate shadows more efficiently than ray-tracing
3636 and produce similar results. Use this when you wish to plot the
3637 occlusion effect that nearby meshes have on each other by blocking
3638 nearby light sources.
3639
3640 See `Kitware: Screen-Space Ambient Occlusion
3641 <https://www.kitware.com/ssao/>`_ for more details
3642
3643 Parameters
3644 ----------
3645 radius : float, default: 0.5
3646 Neighbor pixels considered when computing the occlusion.
3647
3648 bias : float, default: 0.005
3649 Tolerance factor used when comparing pixel depth.
3650
3651 kernel_size : int, default: 256
3652 Number of samples used. This controls the quality where a higher
3653 number increases the quality at the expense of computation time.
3654
3655 blur : bool, default: True
3656 Controls if occlusion buffer should be blurred before combining it
3657 with the color buffer.
3658
3659 See Also
3660 --------
3661 :ref:`ssao_example`
3662
3663 Examples
3664 --------
3665 Generate a :class:`pyvista.UnstructuredGrid` with many tetrahedrons
3666 nearby each other and plot it without SSAO.
3667
3668 >>> import pyvista as pv
3669 >>> ugrid = pv.ImageData(dimensions=(3, 2, 2)).to_tetrahedra(12)
3670 >>> exploded = ugrid.explode()
3671 >>> exploded.plot()
3672
3673 Enable SSAO with the default parameters.
3674
3675 >>> pl = pv.Plotter()
3676 >>> _ = pl.add_mesh(exploded)
3677 >>> pl.enable_ssao()
3678 >>> pl.show()
3679
3680 """
3681 self._render_passes.enable_ssao_pass(
3682 radius=radius, bias=bias, kernel_size=kernel_size, blur=blur
3683 )
3684
3685 def disable_ssao(self) -> None:
3686 """Disable surface space ambient occlusion (SSAO)."""
3687 self._render_passes.disable_ssao_pass()
3688
3689 def get_pick_position(self):
3690 """Get the pick position/area as ``x0, y0, x1, y1``.
3691
3692 Returns
3693 -------
3694 tuple
3695 Pick position as ``x0, y0, x1, y1``.
3696
3697 """
3698 x0 = int(self.GetPickX1())
3699 x1 = int(self.GetPickX2())
3700 y0 = int(self.GetPickY1())
3701 y1 = int(self.GetPickY2())
3702 return x0, y0, x1, y1
3703
3704 @_deprecate_positional_args(allowed=['color'])
3705 def set_background( # noqa: PLR0917
3706 self, color, top=None, right=None, side=None, corner=None
3707 ):
3708 """Set the background color of this renderer.
3709
3710 Parameters
3711 ----------
3712 color : ColorLike, optional
3713 Either a string, rgb list, or hex color string. Defaults
3714 to theme default. For example:
3715
3716 * ``color='white'``
3717 * ``color='w'``
3718 * ``color=[1.0, 1.0, 1.0]``
3719 * ``color='#FFFFFF'``
3720
3721 top : ColorLike, optional
3722 If given, this will enable a gradient background where the
3723 ``color`` argument is at the bottom and the color given in
3724 ``top`` will be the color at the top of the renderer.
3725
3726 right : ColorLike, optional
3727 If given, this will enable a gradient background where the
3728 ``color`` argument is at the left and the color given in
3729 ``right`` will be the color at the right of the renderer.
3730
3731 side : ColorLike, optional
3732 If given, this will enable a gradient background where the
3733 ``color`` argument is at the center and the color given in
3734 ``side`` will be the color at the side of the renderer.
3735
3736 corner : ColorLike, optional
3737 If given, this will enable a gradient background where the
3738 ``color`` argument is at the center and the color given in
3739 ``corner`` will be the color at the corner of the renderer.
3740
3741 Examples
3742 --------
3743 Set the background color to black with a gradient to white at
3744 the top of the plot.
3745
3746 >>> import pyvista as pv
3747 >>> pl = pv.Plotter()
3748 >>> actor = pl.add_mesh(pv.Cone())
3749 >>> pl.set_background('black', top='white')
3750 >>> pl.show()
3751
3752 """
3753 self.SetBackground(Color(color, default_color=self._theme.background).float_rgb)
3754 if not (right is side is corner is None) and vtk_version_info < (
3755 9,
3756 3,
3757 ): # pragma: no cover
3758 from pyvista.core.errors import VTKVersionError
3759
3760 msg = (
3761 '`right` or `side` or `corner` cannot be used under VTK v9.3.0. '
3762 'Try installing VTK v9.3.0 or newer.'
3763 )
3764 raise VTKVersionError(msg)
3765 if not (
3766 (top is right is side is corner is None)
3767 or (top is not None and right is side is corner is None)
3768 or (right is not None and top is side is corner is None)
3769 or (side is not None and top is right is corner is None)
3770 or (corner is not None and top is right is side is None)
3771 ): # pragma: no cover
3772 msg = 'You can only set one argument in top, right, side, corner.'
3773 raise ValueError(msg)
3774 if top is not None:
3775 self.SetGradientBackground(True)
3776 self.SetBackground2(Color(top).float_rgb)
3777 elif right is not None: # pragma: no cover
3778 self.SetGradientBackground(True)
3779 self.SetGradientMode(_vtk.vtkViewport.GradientModes.VTK_GRADIENT_HORIZONTAL)
3780 self.SetBackground2(Color(right).float_rgb)
3781 elif side is not None: # pragma: no cover
3782 self.SetGradientBackground(True)
3783 self.SetGradientMode(
3784 _vtk.vtkViewport.GradientModes.VTK_GRADIENT_RADIAL_VIEWPORT_FARTHEST_SIDE,
3785 )
3786 self.SetBackground2(Color(side).float_rgb)
3787 elif corner is not None: # pragma: no cover
3788 self.SetGradientBackground(True)
3789 self.SetGradientMode(
3790 _vtk.vtkViewport.GradientModes.VTK_GRADIENT_RADIAL_VIEWPORT_FARTHEST_CORNER,
3791 )
3792 self.SetBackground2(Color(corner).float_rgb)
3793 else:
3794 self.SetGradientBackground(False)
3795 self.Modified()
3796
3797 @_deprecate_positional_args(allowed=['texture'])
3798 def set_environment_texture( # noqa: PLR0917
3799 self,
3800 texture,
3801 is_srgb=False, # noqa: FBT002
3802 resample: bool | float | None = None, # noqa: FBT001
3803 rotation: RotationLike | None = None,
3804 show_background=True, # noqa: FBT002
3805 ) -> None:
3806 """Set the environment texture used for image based lighting.
3807
3808 This texture is supposed to represent the scene background. If
3809 it is not a cubemap, the texture is supposed to represent an
3810 equirectangular projection. If used with raytracing backends,
3811 the texture must be an equirectangular projection and must be
3812 constructed with a valid :vtk:`vtkImageData`.
3813
3814 Parameters
3815 ----------
3816 texture : pyvista.Texture
3817 Texture.
3818
3819 is_srgb : bool, default: False
3820 If the texture is in sRGB color space, set the color flag on the
3821 texture or set this parameter to ``True``. Textures are assumed
3822 to be in linear color space by default.
3823
3824 resample : bool | float, optional
3825 Resample the environment texture. Set this to a float to set the
3826 sampling rate explicitly or set to ``True`` to downsample the
3827 texture to 1/16th of its original resolution. By default, the
3828 theme value for ``resample_environment_texture`` is used, which
3829 is ``False`` for the standard theme.
3830
3831 Downsampling the texture can substantially improve performance for
3832 some environments, e.g. headless setups or if GPU support is limited.
3833
3834 .. note::
3835
3836 This will resample the texture used for image-based lighting only,
3837 e.g. the texture used for rendering reflective surfaces. It
3838 does `not` resample the background texture.
3839
3840 .. versionadded:: 0.45
3841
3842 .. versionchanged:: 0.48
3843
3844 Resampling now uses linear interpolation with anti-aliasing
3845 instead of nearest-neighbor, which gives smoother results for
3846 continuous environment textures.
3847
3848 rotation : RotationLike, optional
3849 Rotation to apply to the environment texture for image-based
3850 lighting and the background texture. Accepts any 3x3
3851 :class:`numpy.ndarray`, :vtk:`vtkMatrix3x3`, or SciPy ``Rotation``.
3852 Requires VTK >= 9.6.
3853
3854 .. versionadded:: 0.48
3855
3856 show_background : bool, default: True
3857 Whether to also show the environment texture as the renderer
3858 background. Set this to ``False`` to keep image-based lighting
3859 enabled while using a solid or gradient background instead.
3860
3861 .. versionadded:: 0.48
3862
3863 Examples
3864 --------
3865 Add a skybox cubemap as an environment texture and show that the
3866 lighting from the texture is mapped on to a sphere dataset. Note how
3867 even when disabling the default lightkit, the scene lighting will still
3868 be mapped onto the actor.
3869
3870 >>> from pyvista import examples
3871 >>> import pyvista as pv
3872 >>> pl = pv.Plotter(lighting=None)
3873 >>> cubemap = examples.download_sky_box_cube_map()
3874 >>> _ = pl.add_mesh(pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4)
3875 >>> pl.set_environment_texture(cubemap)
3876 >>> pl.camera_position = 'xy'
3877 >>> pl.show()
3878
3879 """
3880 # cube_map textures cannot use spherical harmonics
3881 if texture.cube_map:
3882 self.AutomaticLightCreationOff()
3883 self.UseSphericalHarmonicsOff()
3884
3885 self.UseImageBasedLightingOn()
3886
3887 if resample is None:
3888 resample = pv.global_theme.resample_environment_texture
3889
3890 if resample:
3891 resample = 1 / 16 if resample is True else resample
3892
3893 # Copy the texture
3894 # TODO: use Texture.copy() once support for cubemaps is added, see https://github.com/pyvista/pyvista/issues/7300
3895 texture_copy = pv.Texture() # type: ignore[abstract]
3896 texture_copy.cube_map = texture.cube_map
3897 texture_copy.mipmap = texture.mipmap
3898 texture_copy.interpolate = texture.interpolate
3899 texture_copy.color_mode = texture.color_mode
3900
3901 # Resample the texture's images
3902 for i in range(6 if texture_copy.cube_map else 1):
3903 old_image = pv.wrap(texture.GetInputDataObject(i, 0))
3904 new_image = old_image.resample(resample, 'linear', anti_aliasing=True)
3905 texture_copy.SetInputDataObject(i, new_image)
3906 self.SetEnvironmentTexture(texture_copy, is_srgb)
3907 else:
3908 self.SetEnvironmentTexture(texture, is_srgb)
3909
3910 if rotation is not None:
3911 if vtk_version_info < (9, 6): # pragma: no cover
3912 from pyvista.core.errors import VTKVersionError
3913
3914 msg = '`rotation` requires VTK >= 9.6. Try installing VTK v9.6.0 or newer.'
3915 raise VTKVersionError(msg)
3916 rotation_matrix = _validation.validate_rotation(
3917 rotation,
3918 must_have_handedness='right',
3919 name='rotation',
3920 )
3921 self.SetEnvironmentRotationMatrix(pv.vtkmatrix_from_array(rotation_matrix))
3922
3923 self.SetBackgroundTexture(texture if show_background else None) # type: ignore[arg-type]
3924 self.Modified()
3925
3926 def remove_environment_texture(self) -> None:
3927 """Remove the environment texture.
3928
3929 Examples
3930 --------
3931 >>> from pyvista import examples
3932 >>> import pyvista as pv
3933 >>> pl = pv.Plotter(lighting=None)
3934 >>> cubemap = examples.download_sky_box_cube_map()
3935 >>> _ = pl.add_mesh(pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4)
3936 >>> pl.set_environment_texture(cubemap)
3937 >>> pl.remove_environment_texture()
3938 >>> pl.camera_position = 'xy'
3939 >>> pl.show()
3940
3941 """
3942 self.UseImageBasedLightingOff()
3943 self.SetEnvironmentTexture(None)
3944 self.SetBackgroundTexture(None) # type: ignore[arg-type]
3945 self.Modified()
3946
3947 def close(self) -> None:
3948 """Close out widgets and sensitive elements."""
3949 self.RemoveAllObservers()
3950 self._remove_axes_widget()
3951
3952 self._bounding_box = None
3953 self._box_object = None
3954 self._marker_actor = None
3955
3956 if self._empty_str is not None:
3957 self._empty_str.SetReferenceCount(0)
3958 self._empty_str = None
3959
3960 # Remove ref to `vtkPropCollection` held by vtkRenderer
3961 if hasattr(self, '_actors'):
3962 del self._actors
3963
3964 self._closed = True
3965
3966 def on_plotter_render(self) -> None:
3967 """Notify renderer components of explicit plotter render call."""
3968 if self._charts is not None:
3969 for chart in self._charts:
3970 # Notify Charts that plotter.render() is called
3971 chart._render_event(plotter_render=True)
3972
3973 @_deprecate_positional_args
3974 def deep_clean(self, render=False) -> None: # noqa: FBT002
3975 """Clean the renderer of the memory.
3976
3977 Parameters
3978 ----------
3979 render : bool, optional
3980 Render the render window after removing the bounding box
3981 (if applicable).
3982
3983 """
3984 if self.cube_axes_actor is not None:
3985 self.cube_axes_actor = None
3986
3987 if hasattr(self, 'edl_pass'):
3988 del self.edl_pass
3989 if self._box_object is not None:
3990 self.remove_bounding_box(render=render)
3991 if self._shadow_pass is not None:
3992 self.disable_shadows() # type: ignore[unreachable]
3993 try:
3994 if self._charts is not None:
3995 self._charts.deep_clean()
3996 self._charts = None
3997 except AttributeError: # pragma: no cover
3998 pass
3999
4000 self._render_passes.deep_clean()
4001 self.remove_floors(render=render)
4002 self.remove_legend(render=render)
4003 self.RemoveAllViewProps()
4004 self._camera = None
4005 self._bounding_box = None
4006 self._marker_actor = None
4007 self._border_actor = None
4008 self._box_object = None
4009 # remove reference to parent last
4010 self.parent = None
4011
4012 def __del__(self) -> None:
4013 """Delete the renderer."""
4014 self.deep_clean()
4015
4016 def enable_hidden_line_removal(self) -> None:
4017 """Enable hidden line removal."""
4018 self.UseHiddenLineRemovalOn()
4019
4020 def disable_hidden_line_removal(self) -> None:
4021 """Disable hidden line removal."""
4022 self.UseHiddenLineRemovalOff()
4023
4024 @property
4025 def layer(self): # numpydoc ignore=RT01
4026 """Return or set the current layer of this renderer."""
4027 return self.GetLayer()
4028
4029 @layer.setter
4030 def layer(self, layer) -> None:
4031 self.SetLayer(layer)
4032
4033 @property
4034 def viewport(self): # numpydoc ignore=RT01
4035 """Viewport of the renderer.
4036
4037 Viewport describes the ``(xstart, ystart, xend, yend)`` square
4038 of the renderer relative to the main renderer window.
4039
4040 For example, a renderer taking up the entire window will have
4041 a viewport of ``(0.0, 0.0, 1.0, 1.0)``, while the viewport of
4042 a renderer on the left-hand side of a horizontally split window
4043 would be ``(0.0, 0.0, 0.5, 1.0)``.
4044
4045 Returns
4046 -------
4047 tuple
4048 Viewport in the form ``(xstart, ystart, xend, yend)``.
4049
4050 Examples
4051 --------
4052 Show the viewport of a renderer taking up half the render
4053 window.
4054
4055 >>> import pyvista as pv
4056 >>> pl = pv.Plotter(shape=(1, 2))
4057 >>> _ = pl.add_mesh(pv.Sphere())
4058 >>> pl.renderers[0].viewport
4059 (0.0, 0.0, 0.5, 1.0)
4060
4061 Change viewport to half size.
4062
4063 >>> pl.renderers[0].viewport = (0.125, 0.25, 0.375, 0.75)
4064 >>> pl.show()
4065
4066 """
4067 return self.GetViewport()
4068
4069 @viewport.setter
4070 def viewport(self, viewport) -> None:
4071 self.SetViewport(viewport)
4072
4073 @property
4074 def width(self): # numpydoc ignore=RT01
4075 """Width of the renderer."""
4076 xmin, _, xmax, _ = self.viewport
4077 return self.parent.window_size[0] * (xmax - xmin)
4078
4079 @property
4080 def height(self): # numpydoc ignore=RT01
4081 """Height of the renderer."""
4082 _, ymin, _, ymax = self.viewport
4083 return self.parent.window_size[1] * (ymax - ymin)
4084
4085 @_deprecate_positional_args(allowed=['labels'])
4086 def add_legend( # noqa: PLR0917
4087 self,
4088 labels=None,
4089 bcolor=None,
4090 border=False, # noqa: FBT002
4091 size=(0.2, 0.2),
4092 name=None,
4093 loc='upper right',
4094 face=None,
4095 font_family=None,
4096 background_opacity=1.0,
4097 ):
4098 """Add a legend to render window.
4099
4100 Entries must be a list containing one string and color entry for each
4101 item.
4102
4103 Parameters
4104 ----------
4105 labels : list | dict, optional
4106 When set to ``None``, uses existing labels as specified by
4107
4108 - :func:`add_mesh <Plotter.add_mesh>`
4109 - :func:`add_lines <Plotter.add_lines>`
4110 - :func:`add_points <Plotter.add_points>`
4111
4112 For dict inputs, the keys are used as labels and the values are used
4113 as the colors. Labels must be strings, and colors can be any
4114 :class:`~pyvista.ColorLike`.
4115
4116 For list inputs, the list must contain one entry for each item to
4117 be added to the legend. Each entry can contain one of the following:
4118
4119 * Two strings ([label, color]), where ``label`` is the name of the
4120 item to add, and ``color`` is the color of the label to add.
4121 * Three strings ([label, color, face]) where ``label`` is the name
4122 of the item to add, ``color`` is the color of the label to add,
4123 and ``face`` is a string which defines the face (i.e. ``circle``,
4124 ``triangle``, ``box``, etc.).
4125 ``face`` could be also ``"none"`` (no face shown for the entry),
4126 or a :class:`pyvista.PolyData`.
4127 * A dict with the key ``label``. Optionally you can add the
4128 keys ``color`` and ``face``. The values of these keys can be
4129 strings. For the ``face`` key, it can be also a
4130 :class:`pyvista.PolyData`.
4131
4132 bcolor : ColorLike, default: (0.5, 0.5, 0.5)
4133 Background color, either a three item 0 to 1 RGB color
4134 list, or a matplotlib color string (e.g. ``'w'`` or ``'white'``
4135 for a white color). If None, legend background is
4136 disabled.
4137
4138 border : bool, default: False
4139 Controls if there will be a border around the legend.
4140 Default False.
4141
4142 size : sequence[float], default: (0.2, 0.2)
4143 Two float sequence, each float between 0 and 1. For example
4144 ``(0.1, 0.1)`` would make the legend 10% the size of the
4145 entire figure window.
4146
4147 name : str, optional
4148 The name for the added actor so that it can be easily
4149 updated. If an actor of this name already exists in the
4150 rendering window, it will be replaced by the new actor.
4151
4152 loc : str, default: "upper right"
4153 Location string. One of the following:
4154
4155 * ``'upper right'``
4156 * ``'upper left'``
4157 * ``'lower left'``
4158 * ``'lower right'``
4159 * ``'center left'``
4160 * ``'center right'``
4161 * ``'lower center'``
4162 * ``'upper center'``
4163 * ``'center'``
4164
4165 face : str | pyvista.PolyData, optional
4166 Face shape of legend face. Defaults to a triangle for most meshes,
4167 with the exception of glyphs where the glyph is shown
4168 (e.g. arrows).
4169
4170 You may set it to one of the following:
4171
4172 * None: ``"none"``
4173 * Line: ``"-"`` or ``"line"``
4174 * Triangle: ``"^"`` or ``'triangle'``
4175 * Circle: ``"o"`` or ``'circle'``
4176 * Rectangle: ``"r"`` or ``'rectangle'``
4177 * Custom: :class:`pyvista.PolyData`
4178
4179 Passing ``"none"`` removes the legend face. A custom face can be
4180 created using :class:`pyvista.PolyData`. This will be rendered
4181 from the XY plane.
4182
4183 font_family : str, optional
4184 Font family. Must be either ``'courier'``, ``'times'``,
4185 or ``'arial'``. Defaults to :attr:`pyvista.global_theme.font.family
4186 <pyvista.plotting.themes._Font.family>`.
4187
4188 background_opacity : float, default: 1.0
4189 Set background opacity.
4190
4191 Returns
4192 -------
4193 :vtk:`vtkLegendBoxActor`
4194 Actor for the legend.
4195
4196 See Also
4197 --------
4198 :ref:`legend_example`
4199
4200 Examples
4201 --------
4202 Create a legend by labeling the meshes when using ``add_mesh``
4203
4204 >>> import pyvista as pv
4205 >>> from pyvista import examples
4206 >>> sphere = pv.Sphere(center=(0, 0, 1))
4207 >>> cube = pv.Cube()
4208 >>> pl = pv.Plotter()
4209 >>> _ = pl.add_mesh(sphere, color='grey', smooth_shading=True, label='Sphere')
4210 >>> _ = pl.add_mesh(cube, color='r', label='Cube')
4211 >>> _ = pl.add_legend(bcolor='w', face=None)
4212 >>> pl.show()
4213
4214 Alternatively provide labels in the plotter as a list.
4215
4216 >>> pl = pv.Plotter()
4217 >>> _ = pl.add_mesh(sphere, color='grey', smooth_shading=True)
4218 >>> _ = pl.add_mesh(cube, color='r')
4219 >>> legend_entries = []
4220 >>> legend_entries.append(['My Mesh', 'w'])
4221 >>> legend_entries.append(['My Other Mesh', 'k'])
4222 >>> _ = pl.add_legend(legend_entries)
4223 >>> pl.show()
4224
4225 Or use a dictionary to define them.
4226
4227 >>> labels = {'Grey Stuff': 'grey', 'Red Stuff': 'red'}
4228 >>> pl = pv.Plotter()
4229 >>> _ = pl.add_mesh(sphere, color='grey', smooth_shading=True)
4230 >>> _ = pl.add_mesh(cube, color='red')
4231 >>> _ = pl.add_legend(labels, face='rectangle')
4232 >>> pl.show()
4233
4234 """
4235 if self.legend is not None:
4236 self.remove_legend()
4237 self._legend = _vtk.vtkLegendBoxActor()
4238
4239 if labels is None:
4240 # use existing labels
4241 if not self._labels:
4242 msg = (
4243 'No labels input.\n\n'
4244 'Add labels to individual items when adding them to'
4245 'the plotting object with the "label=" parameter. '
4246 'or enter them as the "labels" parameter.'
4247 )
4248 raise ValueError(msg)
4249
4250 self._legend.SetNumberOfEntries(len(self._labels))
4251 for i, (vtk_object, text, color) in enumerate(self._labels.values()):
4252 vtk_object_input = make_legend_face(face) if face is not None else vtk_object
4253 self._legend.SetEntry(i, vtk_object_input, text, list(color.float_rgb))
4254
4255 else:
4256 self._legend.SetNumberOfEntries(len(labels))
4257
4258 if isinstance(labels, dict):
4259 face = 'triangle' if face is None else face
4260 labels = list(labels.items())
4261
4262 for i, args in enumerate(labels):
4263 face_ = None
4264 if isinstance(args, (list, tuple)):
4265 if len(args) == 2:
4266 # format labels = [[ text1, color1], [ text2, color2], etc]
4267 text, color = args
4268 else:
4269 # format labels = [[ text1, color1, face1], [ text2, color2, face2], etc]
4270 # Pikcing only the first 3 elements
4271 text, color, face_ = args[:3]
4272 elif isinstance(args, dict):
4273 # it is using a dict
4274 text = args.pop('label')
4275 color = args.pop('color', None)
4276 face_ = args.pop('face', None)
4277
4278 if args:
4279 warn_external(
4280 f'Some of the arguments given to legend are not used.\n{args}'
4281 )
4282 elif isinstance(args, str):
4283 # Only passing label
4284 text = args
4285 # taking the currents (if any)
4286 try:
4287 face_, _, color = list(self._labels.values())[i]
4288 except (AttributeError, IndexError):
4289 # There are no values
4290 face_ = None
4291 color = None
4292
4293 else:
4294 msg = f'The object passed to the legend ({type(args)}) is not valid.'
4295 raise TypeError(msg)
4296
4297 legend_face = make_legend_face(face_ or face)
4298 self._legend.SetEntry(i, legend_face, str(text), list(Color(color).float_rgb))
4299
4300 if loc is not None:
4301 if loc not in ACTOR_LOC_MAP:
4302 allowed = '\n'.join([f'\t * "{item}"' for item in ACTOR_LOC_MAP])
4303 msg = f'Invalid loc "{loc}". Expected one of the following:\n{allowed}'
4304 raise ValueError(msg)
4305 x, y, size = map_loc_to_pos(loc, size, border=0.05)
4306 self._legend.SetPosition(x, y)
4307 self._legend.SetPosition2(size[0], size[1])
4308
4309 if bcolor is None:
4310 self._legend.SetUseBackground(False)
4311 else:
4312 self._legend.SetUseBackground(True)
4313 self._legend.SetBackgroundColor(Color(bcolor).float_rgb)
4314
4315 self._legend.SetBorder(border)
4316
4317 if font_family is None:
4318 font_family = self._theme.font.family
4319
4320 font_family = parse_font_family(font_family)
4321 self._legend.GetEntryTextProperty().SetFontFamily(font_family)
4322
4323 self._legend.SetBackgroundOpacity(background_opacity)
4324
4325 self.add_actor(self._legend, reset_camera=False, name=name, pickable=False)
4326 return self._legend
4327
4328 @_deprecate_positional_args
4329 def remove_legend(self, render=True) -> None: # noqa: FBT002
4330 """Remove the legend actor.
4331
4332 Parameters
4333 ----------
4334 render : bool, default: True
4335 Render upon actor removal. Set this to ``False`` to stop
4336 the render window from rendering when a the legend is removed.
4337
4338 Examples
4339 --------
4340 >>> import pyvista as pv
4341 >>> mesh = pv.Sphere()
4342 >>> pl = pv.Plotter()
4343 >>> _ = pl.add_mesh(mesh, label='sphere')
4344 >>> _ = pl.add_legend()
4345 >>> pl.remove_legend()
4346
4347 """
4348 if self.legend is not None:
4349 self.remove_actor(self.legend, reset_camera=False, render=render)
4350 self._legend = None
4351
4352 @property
4353 def legend(self): # numpydoc ignore=RT01
4354 """Legend actor."""
4355 return self._legend
4356
4357 @_deprecate_positional_args(allowed=['pointa', 'pointb'])
4358 def add_ruler( # noqa: PLR0917
4359 self,
4360 pointa,
4361 pointb,
4362 flip_range=False, # noqa: FBT002
4363 number_labels=None,
4364 show_labels=True, # noqa: FBT002
4365 font_size_factor=0.6,
4366 label_size_factor=1.0,
4367 label_format=None,
4368 title='Distance',
4369 number_minor_ticks=0,
4370 tick_length=5,
4371 minor_tick_length=3,
4372 show_ticks=True, # noqa: FBT002
4373 tick_label_offset=2,
4374 label_color=None,
4375 tick_color=None,
4376 scale=1.0,
4377 ):
4378 """Add ruler.
4379
4380 The ruler is a 2D object that is not occluded by 3D objects.
4381 To avoid issues with perspective, it is recommended to use
4382 parallel projection, i.e. :func:`Plotter.enable_parallel_projection`,
4383 and place the ruler orthogonal to the viewing direction.
4384
4385 The title and labels are placed to the right of ruler moving from
4386 ``pointa`` to ``pointb``. Use ``flip_range`` to flip the ``0`` location,
4387 if needed.
4388
4389 Since the ruler is placed in an overlay on the viewing scene, the camera
4390 does not automatically reset to include the ruler in the view.
4391
4392 Parameters
4393 ----------
4394 pointa : sequence[float]
4395 Starting point for ruler.
4396
4397 pointb : sequence[float]
4398 Ending point for ruler.
4399
4400 flip_range : bool, default: False
4401 If ``True``, the distance range goes from ``pointb`` to ``pointa``.
4402
4403 number_labels : int, optional
4404 Number of labels to place on ruler.
4405 If not supplied, the number will be adjusted for "nice" values.
4406
4407 show_labels : bool, default: True
4408 Whether to show labels.
4409
4410 font_size_factor : float, default: 0.6
4411 Factor to scale font size overall.
4412
4413 label_size_factor : float, default: 1.0
4414 Factor to scale label size relative to title size.
4415
4416 label_format : str, optional
4417 A printf style format for labels, e.g. '%E'.
4418
4419 title : str, default: "Distance"
4420 The title to display.
4421
4422 number_minor_ticks : int, default: 0
4423 Number of minor ticks between major ticks.
4424
4425 tick_length : int, default: 5
4426 Length of ticks in pixels.
4427
4428 minor_tick_length : int, default: 3
4429 Length of minor ticks in pixels.
4430
4431 show_ticks : bool, default: True
4432 Whether to show the ticks.
4433
4434 tick_label_offset : int, default: 2
4435 Offset between tick and label in pixels.
4436
4437 label_color : ColorLike, optional
4438 Either a string, rgb list, or hex color string for
4439 label and title colors.
4440
4441 .. warning::
4442 This is either white or black.
4443
4444 tick_color : ColorLike, optional
4445 Either a string, rgb list, or hex color string for
4446 tick line colors.
4447
4448 scale : float, default: 1.0
4449 Scale factor for the ruler.
4450
4451 .. versionadded:: 0.44.0
4452
4453 Returns
4454 -------
4455 :vtk:`vtkActor`
4456 VTK actor of the ruler.
4457
4458 Examples
4459 --------
4460 >>> import pyvista as pv
4461 >>> cone = pv.Cone(height=2.0, radius=0.5)
4462 >>> pl = pv.Plotter()
4463 >>> _ = pl.add_mesh(cone)
4464
4465 Measure x direction of cone and place ruler slightly below.
4466
4467 >>> _ = pl.add_ruler(
4468 ... pointa=[cone.bounds.x_min, cone.bounds.y_min - 0.1, 0.0],
4469 ... pointb=[cone.bounds.x_max, cone.bounds.y_min - 0.1, 0.0],
4470 ... title='X Distance',
4471 ... )
4472
4473 Measure y direction of cone and place ruler slightly to left.
4474 The title and labels are placed to the right of the ruler when
4475 traveling from ``pointa`` to ``pointb``.
4476
4477 >>> _ = pl.add_ruler(
4478 ... pointa=[cone.bounds.x_min - 0.1, cone.bounds.y_max, 0.0],
4479 ... pointb=[cone.bounds.x_min - 0.1, cone.bounds.y_min, 0.0],
4480 ... flip_range=True,
4481 ... title='Y Distance',
4482 ... )
4483 >>> pl.enable_parallel_projection()
4484 >>> pl.view_xy()
4485 >>> pl.show()
4486
4487 """
4488 label_color = Color(label_color, default_color=self._theme.font.color)
4489 tick_color = Color(tick_color, default_color=self._theme.font.color)
4490
4491 ruler = _vtk.vtkAxisActor2D()
4492
4493 ruler.GetPositionCoordinate().SetCoordinateSystemToWorld()
4494 ruler.GetPosition2Coordinate().SetCoordinateSystemToWorld()
4495 ruler.GetPositionCoordinate().SetReferenceCoordinate(None) # type: ignore[arg-type]
4496 ruler.GetPositionCoordinate().SetValue(pointa[0], pointa[1], pointa[2])
4497 ruler.GetPosition2Coordinate().SetValue(pointb[0], pointb[1], pointb[2])
4498
4499 distance = np.linalg.norm(np.asarray(pointa) - np.asarray(pointb))
4500 if flip_range:
4501 ruler.SetRange(distance * scale, 0)
4502 else:
4503 ruler.SetRange(0, distance * scale)
4504
4505 ruler.SetTitle(title)
4506 ruler.SetFontFactor(font_size_factor)
4507 ruler.SetLabelFactor(label_size_factor)
4508 if number_labels is not None:
4509 ruler.AdjustLabelsOff()
4510 ruler.SetNumberOfLabels(number_labels)
4511 ruler.SetLabelVisibility(show_labels)
4512 if label_format:
4513 ruler.SetLabelFormat(label_format)
4514 ruler.GetProperty().SetColor(*tick_color.int_rgb)
4515 if label_color != Color('white'):
4516 # This property turns black if set
4517 ruler.GetLabelTextProperty().SetColor(*label_color.int_rgb)
4518 ruler.GetTitleTextProperty().SetColor(*label_color.int_rgb)
4519 ruler.SetNumberOfMinorTicks(number_minor_ticks)
4520 ruler.SetTickVisibility(show_ticks)
4521 ruler.SetTickLength(tick_length)
4522 ruler.SetMinorTickLength(minor_tick_length)
4523 ruler.SetTickOffset(tick_label_offset)
4524
4525 self.add_actor(ruler, reset_camera=True, pickable=False)
4526 return ruler
4527
4528 @_deprecate_positional_args
4529 def add_legend_scale( # noqa: PLR0917
4530 self,
4531 corner_offset_factor=2.0,
4532 bottom_border_offset=30,
4533 top_border_offset=30,
4534 left_border_offset=30,
4535 right_border_offset=30,
4536 bottom_axis_visibility=True, # noqa: FBT002
4537 top_axis_visibility=True, # noqa: FBT002
4538 left_axis_visibility=True, # noqa: FBT002
4539 right_axis_visibility=True, # noqa: FBT002
4540 legend_visibility=True, # noqa: FBT002
4541 xy_label_mode=False, # noqa: FBT002
4542 render=True, # noqa: FBT002
4543 color=None,
4544 font_size_factor=0.6,
4545 label_size_factor=1.0,
4546 label_format=None,
4547 number_minor_ticks=0,
4548 tick_length=5,
4549 minor_tick_length=3,
4550 show_ticks=True, # noqa: FBT002
4551 tick_label_offset=2,
4552 ):
4553 """Annotate the render window with scale and distance information.
4554
4555 Its basic goal is to provide an indication of the scale of the scene.
4556 Four axes surrounding the render window indicate (in a variety of ways)
4557 the scale of what the camera is viewing. An option also exists for
4558 displaying a scale legend.
4559
4560 Parameters
4561 ----------
4562 corner_offset_factor : float, default: 2.0
4563 The corner offset value.
4564
4565 bottom_border_offset : int, default: 30
4566 Bottom border offset. Recommended value ``50``.
4567
4568 top_border_offset : int, default: 30
4569 Top border offset. Recommended value ``50``.
4570
4571 left_border_offset : int, default: 30
4572 Left border offset. Recommended value ``100``.
4573
4574 right_border_offset : int, default: 30
4575 Right border offset. Recommended value ``100``.
4576
4577 bottom_axis_visibility : bool, default: True
4578 Whether the bottom axis is visible.
4579
4580 top_axis_visibility : bool, default: True
4581 Whether the top axis is visible.
4582
4583 left_axis_visibility : bool, default: True
4584 Whether the left axis is visible.
4585
4586 right_axis_visibility : bool, default: True
4587 Whether the right axis is visible.
4588
4589 legend_visibility : bool, default: True
4590 Whether the legend scale is visible.
4591
4592 xy_label_mode : bool, default: False
4593 The axes can be programmed either to display distance scales
4594 or x-y coordinate values. By default,
4595 the scales display a distance. However, if you know that the
4596 view is down the z-axis, the scales can be programmed to display
4597 x-y coordinate values.
4598
4599 render : bool, default: True
4600 Whether to render when the actor is added.
4601
4602 color : ColorLike, optional
4603 Either a string, rgb list, or hex color string for tick text
4604 and tick line colors.
4605
4606 .. warning::
4607 The axis labels tend to be either white or black.
4608
4609 font_size_factor : float, default: 0.6
4610 Factor to scale font size overall.
4611
4612 label_size_factor : float, default: 1.0
4613 Factor to scale label size relative to title size.
4614
4615 label_format : str, optional
4616 A printf style format for labels, e.g. ``'%E'``.
4617 See :ref:`old-string-formatting`.
4618
4619 number_minor_ticks : int, default: 0
4620 Number of minor ticks between major ticks.
4621
4622 tick_length : int, default: 5
4623 Length of ticks in pixels.
4624
4625 minor_tick_length : int, default: 3
4626 Length of minor ticks in pixels.
4627
4628 show_ticks : bool, default: True
4629 Whether to show the ticks.
4630
4631 tick_label_offset : int, default: 2
4632 Offset between tick and label in pixels.
4633
4634 Returns
4635 -------
4636 :vtk:`vtkActor`
4637 The actor for the added :vtk:`vtkLegendScaleActor`.
4638
4639 Warnings
4640 --------
4641 Please be aware that the axes and scale values are subject to perspective
4642 effects. The distances are computed in the focal plane of the camera. When
4643 there are large view angles (i.e., perspective projection), the computed
4644 distances may provide users the wrong sense of scale. These effects are not
4645 present when parallel projection is enabled.
4646
4647 Examples
4648 --------
4649 >>> import pyvista as pv
4650 >>> cone = pv.Cone(height=2.0, radius=0.5)
4651 >>> pl = pv.Plotter()
4652 >>> _ = pl.add_mesh(cone)
4653 >>> _ = pl.add_legend_scale()
4654 >>> pl.show()
4655
4656 """
4657 color = Color(color, default_color=self._theme.font.color)
4658
4659 legend_scale = _vtk.vtkLegendScaleActor()
4660 legend_scale.SetCornerOffsetFactor(corner_offset_factor)
4661 legend_scale.SetLegendVisibility(legend_visibility)
4662 if xy_label_mode:
4663 if pv.vtk_version_info >= (9, 4):
4664 legend_scale.SetLabelModeToCoordinates()
4665 else:
4666 legend_scale.SetLabelModeToXYCoordinates() # type: ignore[attr-defined]
4667 else:
4668 legend_scale.SetLabelModeToDistance()
4669 legend_scale.SetBottomAxisVisibility(bottom_axis_visibility)
4670 legend_scale.SetBottomBorderOffset(bottom_border_offset)
4671 legend_scale.SetLeftAxisVisibility(left_axis_visibility)
4672 legend_scale.SetLeftBorderOffset(left_border_offset)
4673 legend_scale.SetRightAxisVisibility(right_axis_visibility)
4674 legend_scale.SetRightBorderOffset(right_border_offset)
4675 legend_scale.SetTopAxisVisibility(top_axis_visibility)
4676 legend_scale.SetTopBorderOffset(top_border_offset)
4677
4678 for text in ['Label', 'Title']:
4679 prop = getattr(legend_scale, f'GetLegend{text}Property')()
4680 if color != Color('white'):
4681 # This property turns black if set
4682 prop.SetColor(*color.int_rgb)
4683 prop.SetFontSize(
4684 int(font_size_factor * 20),
4685 ) # hack to avoid multiple font size arguments
4686
4687 for ax in ['Bottom', 'Left', 'Right', 'Top']:
4688 axis = getattr(legend_scale, f'Get{ax}Axis')()
4689 axis.GetProperty().SetColor(*color.int_rgb)
4690 if color != Color('white'):
4691 # This label property turns black if set
4692 axis.GetLabelTextProperty().SetColor(*color.int_rgb)
4693 axis.SetFontFactor(font_size_factor)
4694 axis.SetLabelFactor(label_size_factor)
4695 if label_format:
4696 axis.SetLabelFormat(label_format)
4697 axis.SetNumberOfMinorTicks(number_minor_ticks)
4698 axis.SetTickLength(tick_length)
4699 axis.SetMinorTickLength(minor_tick_length)
4700 axis.SetTickVisibility(show_ticks)
4701 axis.SetTickOffset(tick_label_offset)
4702
4703 return self.add_actor(
4704 legend_scale,
4705 reset_camera=False,
4706 name='_vtkLegendScaleActor',
4707 culling=False,
4708 pickable=False,
4709 render=render,
4710 )
4711
4712
4713 def _fixup_bounds(bounds) -> BoundsTuple:
4714 the_bounds = np.asarray(bounds)
4715 if np.any(the_bounds[::2] > the_bounds[1::2]):
4716 the_bounds[:] = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
4717 return BoundsTuple(*the_bounds.tolist())