Debian Codegraph @

pyvista/plotting/cube_axes_actor.py

raw
1 """Module containing the wrapping of CubeAxesActor."""
2
3 from __future__ import annotations
4
5 from collections.abc import MutableSequence
6 from typing import TYPE_CHECKING
7 from typing import cast
8
9 import numpy as np
10
11 import pyvista as pv
12 from pyvista import _vtk
13 from pyvista._deprecate_positional_args import _deprecate_positional_args
14 from pyvista._warn_external import warn_external
15 from pyvista.core._typing_core import BoundsTuple
16 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
17 from pyvista.core.utilities.arrays import convert_string_array
18 from pyvista.core.utilities.misc import _BoundsSizeMixin
19 from pyvista.core.utilities.misc import _NameMixin
20 from pyvista.core.utilities.misc import _NoNewAttrMixin
21
22 if TYPE_CHECKING:
23 from pyvista.core._typing_core import VectorLike
24
25
26 @_deprecate_positional_args
27 def make_axis_labels(vmin, vmax, n, fmt): # noqa: PLR0917
28 """Create axis labels as a :vtk:`vtkStringArray`.
29
30 Parameters
31 ----------
32 vmin : float
33 The minimum value for the axis labels.
34 vmax : float
35 The maximum value for the axis labels.
36 n : int
37 The number of labels to create.
38 fmt : str
39 A format string for the labels. If the string starts with '%', the label will be formatted
40 using the old-style string formatting method.
41 Otherwise, the label will be formatted using the new-style string formatting method.
42
43 Returns
44 -------
45 :vtk:`vtkStringArray`
46 The created labels as a :vtk:`vtkStringArray` object.
47
48 """
49 labels = _vtk.vtkStringArray()
50 for v in np.linspace(vmin, vmax, n):
51 label = (fmt % v if fmt.startswith('%') else fmt.format(v)) if fmt else f'{v}'
52 labels.InsertNextValue(label)
53 return labels
54
55
56 class CubeAxesActor(
57 _NoNewAttrMixin, _NameMixin, _BoundsSizeMixin, DisableVtkSnakeCase, _vtk.vtkCubeAxesActor
58 ):
59 """Wrap :vtk:`vtkCubeAxesActor`.
60
61 This class is created to wrap :vtk:`vtkCubeAxesActor`, which is used to draw axes
62 and labels for the input data bounds. This wrapping aims to provide a
63 user-friendly interface to use :vtk:`vtkCubeAxesActor`.
64
65 Parameters
66 ----------
67 camera : pyvista.Camera
68 Camera to link to the axes actor.
69
70 minor_ticks : bool, default: False
71 If ``True``, also plot minor ticks on all axes.
72
73 tick_location : str, optional
74 Set how the ticks are drawn on the axes grid. Options include:
75 ``'inside', 'outside', 'both'``.
76
77 x_title : str, default: "X Axis"
78 Title of the x-axis.
79
80 y_title : str, default: "Y Axis"
81 Title of the y-axis.
82
83 z_title : str, default: "Z Axis"
84 Title of the z-axis.
85
86 x_axis_visibility : bool, default: True
87 Visibility of the x-axis.
88
89 y_axis_visibility : bool, default: True
90 Visibility of the y-axis.
91
92 z_axis_visibility : bool, default: True
93 Visibility of the z-axis.
94
95 x_label_format : str, optional
96 A format string defining how tick labels are generated from tick
97 positions for the x-axis. Defaults to the theme format if set,
98 otherwise ``'{0:.1f}'``.
99
100 y_label_format : str, optional
101 A format string defining how tick labels are generated from tick
102 positions for the y-axis. Defaults to the theme format if set,
103 otherwise ``'{0:.1f}'``.
104
105 z_label_format : str, optional
106 A format string defining how tick labels are generated from tick
107 positions for the z-axis. Defaults to the theme format if set,
108 otherwise ``'{0:.1f}'``.
109
110 x_label_visibility : bool, default: True
111 The visibility of the x-axis labels.
112
113 y_label_visibility : bool, default: True
114 The visibility of the y-axis labels.
115
116 z_label_visibility : bool, default: True
117 The visibility of the z-axis labels.
118
119 n_xlabels : int, default: 5
120 Number of labels along the x-axis.
121
122 n_ylabels : int, default: 5
123 Number of labels along the y-axis.
124
125 n_zlabels : int, default: 5
126 Number of labels along the z-axis.
127
128 See Also
129 --------
130 :meth:`~pyvista.Plotter.show_bounds`
131 :meth:`~pyvista.Plotter.show_grid`
132 :ref:`axes_objects_example`
133 Example showing different axes objects.
134
135 Examples
136 --------
137 Create a 3D plotter and add a CubeAxesActor to it.
138
139 >>> import pyvista as pv
140 >>> mesh = pv.Cube()
141 >>> pl = pv.Plotter()
142 >>> actor = pl.add_mesh(mesh)
143 >>> cube_axes_actor = pv.CubeAxesActor(pl.camera)
144 >>> cube_axes_actor.bounds = mesh.bounds
145 >>> actor, property = pl.add_actor(cube_axes_actor)
146 >>> pl.show()
147
148 """
149
150 @_deprecate_positional_args(allowed=['camera'])
151 def __init__( # noqa: PLR0917
152 self,
153 camera,
154 minor_ticks: bool = False, # noqa: FBT001, FBT002
155 tick_location=None,
156 x_title='X Axis',
157 y_title='Y Axis',
158 z_title='Z Axis',
159 x_axis_visibility: bool = True, # noqa: FBT001, FBT002
160 y_axis_visibility: bool = True, # noqa: FBT001, FBT002
161 z_axis_visibility: bool = True, # noqa: FBT001, FBT002
162 x_label_format=None,
163 y_label_format=None,
164 z_label_format=None,
165 x_label_visibility: bool = True, # noqa: FBT001, FBT002
166 y_label_visibility: bool = True, # noqa: FBT001, FBT002
167 z_label_visibility: bool = True, # noqa: FBT001, FBT002
168 n_xlabels=5,
169 n_ylabels=5,
170 n_zlabels=5,
171 ):
172 """Initialize CubeAxesActor."""
173 super().__init__()
174 self.camera = camera
175
176 # empty string used for clearing axis labels
177 self._empty_str = _vtk.vtkStringArray()
178 self._empty_str.InsertNextValue('')
179
180 # stop labels from being generated several times during init
181 self.x_axis_visibility = False
182 self.y_axis_visibility = False
183 self.z_axis_visibility = False
184
185 if not minor_ticks:
186 self.x_axis_minor_tick_visibility = minor_ticks
187 self.y_axis_minor_tick_visibility = minor_ticks
188 self.z_axis_minor_tick_visibility = minor_ticks
189
190 if tick_location:
191 self.tick_location = tick_location
192 self.x_title = x_title
193 self.y_title = y_title
194 self.z_title = z_title
195
196 self._x_label_visibility = x_label_visibility
197 self._y_label_visibility = y_label_visibility
198 self._z_label_visibility = z_label_visibility
199
200 default_fmt = '%.1f' if pv.vtk_version_info < (9, 6, 0) else '{0:.1f}'
201 if x_label_format is None:
202 x_label_format = pv.global_theme.font.fmt
203 if x_label_format is None:
204 x_label_format = default_fmt
205 if y_label_format is None:
206 y_label_format = pv.global_theme.font.fmt
207 if y_label_format is None:
208 y_label_format = default_fmt
209 if z_label_format is None:
210 z_label_format = pv.global_theme.font.fmt
211 if z_label_format is None:
212 z_label_format = default_fmt
213
214 self.x_label_format = x_label_format
215 self.y_label_format = y_label_format
216 self.z_label_format = z_label_format
217
218 self.n_xlabels = n_xlabels
219 self.n_ylabels = n_ylabels
220 self.n_zlabels = n_zlabels
221
222 self.x_axis_visibility = x_axis_visibility
223 self.y_axis_visibility = y_axis_visibility
224 self.z_axis_visibility = z_axis_visibility
225
226 @property
227 def tick_location(self) -> str: # numpydoc ignore=RT01
228 """Return or set how the ticks are drawn on the axes grid.
229
230 Options include: ``'inside', 'outside', 'both'``.
231 """
232 tloc = self.GetTickLocation()
233 if tloc == 0:
234 return 'inside'
235 if tloc == 1:
236 return 'outside'
237 return 'both'
238
239 @tick_location.setter
240 def tick_location(self, value: str):
241 if not isinstance(value, str):
242 msg = f'`tick_location` must be a string, not {type(value)}' # type: ignore[unreachable]
243 raise TypeError(msg)
244 value = value.lower()
245 if value in ('inside'):
246 self.SetTickLocationToInside()
247 elif value in ('outside'):
248 self.SetTickLocationToOutside()
249 elif value in ('both'):
250 self.SetTickLocationToBoth()
251 else:
252 msg = (
253 f'Value of tick_location ("{value}") should be either "inside", "outside", '
254 'or "both".'
255 )
256 raise ValueError(msg)
257
258 @property
259 def bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
260 """Return or set the bounding box."""
261 return BoundsTuple(*self.GetBounds())
262
263 @bounds.setter
264 def bounds(self, bounds: VectorLike[float]):
265 self.SetBounds(bounds) # type: ignore[arg-type]
266 self._update_labels()
267 bnds = self.bounds
268 self.x_axis_range = bnds.x_min, bnds.x_max
269 self.y_axis_range = bnds.y_min, bnds.y_max
270 self.z_axis_range = bnds.z_min, bnds.z_max
271
272 @property
273 def center(self) -> tuple[float, float, float]:
274 """Return the center.
275
276 Returns
277 -------
278 tuple[float, float, float]
279 Center of axes actor.
280
281 """
282 return self.GetCenter()
283
284 @property
285 def x_axis_range(self) -> tuple[float, float]: # numpydoc ignore=RT01
286 """Return or set the x-axis range."""
287 return self.GetXAxisRange()
288
289 @x_axis_range.setter
290 def x_axis_range(self, value: tuple[float, float]):
291 self.SetXAxisRange(value)
292 self._update_x_labels()
293
294 @property
295 def y_axis_range(self) -> tuple[float, float]: # numpydoc ignore=RT01
296 """Return or set the y-axis range."""
297 return self.GetYAxisRange()
298
299 @y_axis_range.setter
300 def y_axis_range(self, value: tuple[float, float]):
301 self.SetYAxisRange(value)
302 self._update_y_labels()
303
304 @property
305 def z_axis_range(self) -> tuple[float, float]: # numpydoc ignore=RT01
306 """Return or set the z-axis range."""
307 return self.GetZAxisRange()
308
309 @z_axis_range.setter
310 def z_axis_range(self, value: tuple[float, float]):
311 self.SetZAxisRange(value)
312 self._update_z_labels()
313
314 @property
315 def label_offset(self) -> float: # numpydoc ignore=RT01
316 """Return or set the distance between labels and the axis."""
317 return self.GetLabelOffset()
318
319 @label_offset.setter
320 def label_offset(self, offset: float):
321 self.SetLabelOffset(offset)
322
323 @property
324 def title_offset(self) -> float | tuple[float, float]: # numpydoc ignore=RT01
325 """Return or set the distance between title and labels."""
326 if (9, 3, 0) <= pv.vtk_version_info < (9, 5, 0):
327 offx, offy = (_vtk.reference(0.0), _vtk.reference(0.0))
328 self.GetTitleOffset(offx, offy) # type: ignore[call-arg]
329 return offx, offy # type: ignore[return-value]
330
331 return self.GetTitleOffset()
332
333 @title_offset.setter
334 def title_offset(self, offset: float | MutableSequence[float]):
335 vtk_geq_9_3 = pv.vtk_version_info >= (9, 3)
336
337 if vtk_geq_9_3:
338 if isinstance(offset, float):
339 msg = (
340 f'Setting title_offset with a float is deprecated from vtk >= 9.3. '
341 f'Accepts now a sequence of (x,y) offsets. '
342 f'Setting the x offset to {(x := 0.0)}'
343 )
344 warn_external(msg, UserWarning)
345 self.SetTitleOffset([x, offset])
346 else:
347 self.SetTitleOffset(offset)
348 return
349
350 if isinstance(offset, MutableSequence):
351 msg = (
352 f'Setting title_offset with a sequence is only supported from vtk >= 9.3. '
353 f'Considering only the second value (ie. y-offset) of {(y := offset[1])}'
354 )
355 warn_external(msg, UserWarning)
356 self.SetTitleOffset(y) # type: ignore[arg-type]
357 return
358
359 self.SetTitleOffset(offset) # type: ignore[arg-type]
360
361 @property
362 def camera(self) -> pv.Camera: # numpydoc ignore=RT01
363 """Return or set the camera that performs scaling and translation."""
364 return self.GetCamera()
365
366 @camera.setter
367 def camera(self, camera: pv.Camera):
368 self.SetCamera(camera)
369
370 @property
371 def x_axis_minor_tick_visibility(self) -> bool: # numpydoc ignore=RT01
372 """Return or set visibility of the x-axis minior tick."""
373 return bool(self.GetXAxisMinorTickVisibility())
374
375 @x_axis_minor_tick_visibility.setter
376 def x_axis_minor_tick_visibility(self, value: bool):
377 self.SetXAxisMinorTickVisibility(value)
378
379 @property
380 def y_axis_minor_tick_visibility(self) -> bool: # numpydoc ignore=RT01
381 """Return or set visibility of the y-axis minior tick."""
382 return bool(self.GetYAxisMinorTickVisibility())
383
384 @y_axis_minor_tick_visibility.setter
385 def y_axis_minor_tick_visibility(self, value: bool):
386 self.SetYAxisMinorTickVisibility(value)
387
388 @property
389 def z_axis_minor_tick_visibility(self) -> bool: # numpydoc ignore=RT01
390 """Return or set visibility of the z-axis minior tick."""
391 return bool(self.GetZAxisMinorTickVisibility())
392
393 @z_axis_minor_tick_visibility.setter
394 def z_axis_minor_tick_visibility(self, value: bool):
395 self.SetZAxisMinorTickVisibility(value)
396
397 @property
398 def x_label_visibility(self) -> bool: # numpydoc ignore=RT01
399 """Return or set the visibility of the x-axis labels."""
400 return self._x_label_visibility
401
402 @x_label_visibility.setter
403 def x_label_visibility(self, value: bool):
404 self._x_label_visibility = bool(value)
405 self._update_x_labels()
406
407 @property
408 def y_label_visibility(self) -> bool: # numpydoc ignore=RT01
409 """Return or set the visibility of the y-axis labels."""
410 return self._y_label_visibility
411
412 @y_label_visibility.setter
413 def y_label_visibility(self, value: bool):
414 self._y_label_visibility = bool(value)
415 self._update_y_labels()
416
417 @property
418 def z_label_visibility(self) -> bool: # numpydoc ignore=RT01
419 """Return or set the visibility of the z-axis labels."""
420 return self._z_label_visibility
421
422 @z_label_visibility.setter
423 def z_label_visibility(self, value: bool):
424 self._z_label_visibility = bool(value)
425 self._update_z_labels()
426
427 @property
428 def x_axis_visibility(self) -> bool: # numpydoc ignore=RT01
429 """Return or set the visibility of the x-axis."""
430 return bool(self.GetXAxisVisibility())
431
432 @x_axis_visibility.setter
433 def x_axis_visibility(self, value: bool):
434 self.SetXAxisVisibility(value)
435
436 @property
437 def y_axis_visibility(self) -> bool: # numpydoc ignore=RT01
438 """Return or set the visibility of the y-axis."""
439 return bool(self.GetYAxisVisibility())
440
441 @y_axis_visibility.setter
442 def y_axis_visibility(self, value: bool):
443 self.SetYAxisVisibility(value)
444
445 @property
446 def z_axis_visibility(self) -> bool: # numpydoc ignore=RT01
447 """Return or set the visibility of the y-axis."""
448 return bool(self.GetZAxisVisibility())
449
450 @z_axis_visibility.setter
451 def z_axis_visibility(self, value: bool):
452 self.SetZAxisVisibility(value)
453
454 @property
455 def x_label_format(self) -> str: # numpydoc ignore=RT01
456 """Return or set the label of the x-axis."""
457 return self.GetXLabelFormat()
458
459 @x_label_format.setter
460 def x_label_format(self, value: str):
461 self.SetXLabelFormat(value)
462 self._update_x_labels()
463
464 @property
465 def y_label_format(self) -> str: # numpydoc ignore=RT01
466 """Return or set the label of the y-axis."""
467 return self.GetYLabelFormat()
468
469 @y_label_format.setter
470 def y_label_format(self, value: str):
471 self.SetYLabelFormat(value)
472 self._update_y_labels()
473
474 @property
475 def z_label_format(self) -> str: # numpydoc ignore=RT01
476 """Return or set the label of the z-axis."""
477 return self.GetZLabelFormat()
478
479 @z_label_format.setter
480 def z_label_format(self, value: str):
481 self.SetZLabelFormat(value)
482 self._update_z_labels()
483
484 @property
485 def x_title(self) -> str: # numpydoc ignore=RT01
486 """Return or set the title of the x-axis."""
487 return self._x_title
488
489 @x_title.setter
490 def x_title(self, value: str):
491 self._x_title = value
492 self._update_x_labels()
493
494 @property
495 def y_title(self) -> str: # numpydoc ignore=RT01
496 """Return or set the title of the y-axis."""
497 return self._y_title
498
499 @y_title.setter
500 def y_title(self, value: str):
501 self._y_title = value
502 self._update_y_labels()
503
504 @property
505 def z_title(self) -> str: # numpydoc ignore=RT01
506 """Return or set the title of the z-axis."""
507 return self._z_title
508
509 @z_title.setter
510 def z_title(self, value: str):
511 self._z_title = value
512 self._update_z_labels()
513
514 @property
515 def use_2d_mode(self) -> bool: # numpydoc ignore=RT01
516 """Use the 2d render mode.
517
518 This can be enabled for smoother plotting.
519 """
520 return bool(self.GetUse2DMode())
521
522 @use_2d_mode.setter
523 def use_2d_mode(self, value: bool):
524 self.SetUse2DMode(value)
525
526 @property
527 def n_xlabels(self): # numpydoc ignore=RT01
528 """Number of labels on the x-axis."""
529 return self._n_xlabels
530
531 @n_xlabels.setter
532 def n_xlabels(self, value: int):
533 self._n_xlabels = value
534 self._update_x_labels()
535
536 @property
537 def n_ylabels(self): # numpydoc ignore=RT01
538 """Number of labels on the y-axis."""
539 return self._n_ylabels
540
541 @n_ylabels.setter
542 def n_ylabels(self, value: int):
543 self._n_ylabels = value
544 self._update_y_labels()
545
546 @property
547 def n_zlabels(self): # numpydoc ignore=RT01
548 """Number of labels on the z-axis."""
549 return self._n_zlabels
550
551 @n_zlabels.setter
552 def n_zlabels(self, value: int):
553 self._n_zlabels = value
554 self._update_z_labels()
555
556 def _update_labels(self):
557 """Update all labels."""
558 self._update_x_labels()
559 self._update_y_labels()
560 self._update_z_labels()
561
562 def _update_x_labels(self):
563 """Regenerate x-axis labels."""
564 if self.x_axis_visibility:
565 self.SetXTitle(self._x_title)
566 if self._x_label_visibility:
567 vmin, vmax = self.x_axis_range
568 self.SetAxisLabels(
569 0,
570 make_axis_labels(
571 vmin=vmin, vmax=vmax, n=self.n_xlabels, fmt=self.x_label_format
572 ),
573 )
574 else:
575 self.SetAxisLabels(0, self._empty_str)
576 else:
577 self.SetXTitle(' ')
578 self.SetAxisLabels(0, self._empty_str)
579
580 def _update_y_labels(self):
581 """Regenerate y-axis labels."""
582 if self.y_axis_visibility:
583 self.SetYTitle(self._y_title)
584 if self._y_label_visibility:
585 vmin, vmax = self.y_axis_range
586 self.SetAxisLabels(
587 1,
588 make_axis_labels(
589 vmin=vmin, vmax=vmax, n=self.n_ylabels, fmt=self.y_label_format
590 ),
591 )
592 else:
593 self.SetAxisLabels(1, self._empty_str)
594 else:
595 self.SetYTitle(' ')
596 self.SetAxisLabels(1, self._empty_str)
597
598 def _update_z_labels(self):
599 """Regenerate z-axis labels."""
600 if self.z_axis_visibility:
601 self.SetZTitle(self._z_title)
602 if self._z_label_visibility:
603 vmin, vmax = self.z_axis_range
604 self.SetAxisLabels(
605 2,
606 make_axis_labels(
607 vmin=vmin, vmax=vmax, n=self.n_zlabels, fmt=self.z_label_format
608 ),
609 )
610 else:
611 self.SetAxisLabels(2, self._empty_str)
612 else:
613 self.SetZTitle(' ')
614 self.SetAxisLabels(2, self._empty_str)
615
616 @property
617 def x_labels(self) -> list[str]: # numpydoc ignore=RT01
618 """Return the x-axis labels."""
619 labels_vtk = cast('_vtk.vtkStringArray', self.GetAxisLabels(0))
620 return convert_string_array(labels_vtk).tolist()
621
622 @property
623 def y_labels(self) -> list[str]: # numpydoc ignore=RT01
624 """Return the y-axis labels."""
625 labels_vtk = cast('_vtk.vtkStringArray', self.GetAxisLabels(1))
626 return convert_string_array(labels_vtk).tolist()
627
628 @property
629 def z_labels(self) -> list[str]: # numpydoc ignore=RT01
630 """Return the z-axis labels."""
631 labels_vtk = cast('_vtk.vtkStringArray', self.GetAxisLabels(2))
632 return convert_string_array(labels_vtk).tolist()
633
634 def update_bounds(self, bounds):
635 """Update the bounds of this actor.
636
637 Unlike the :attr:`CubeAxesActor.bounds` attribute, updating the bounds
638 also updates the axis labels.
639
640 Parameters
641 ----------
642 bounds : sequence[float]
643 Bounds in the form of ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
644
645 """
646 self.bounds = bounds