Debian Codegraph @

pyvista/plotting/text.py

raw
1 """Contains the pyvista.Text class."""
2
3 from __future__ import annotations
4
5 import pathlib
6 from pathlib import Path
7 from typing import TYPE_CHECKING
8 from typing import Literal
9
10 import pyvista as pv
11 from pyvista import _vtk
12 from pyvista._deprecate_positional_args import _deprecate_positional_args
13 from pyvista.core import _validation
14 from pyvista.core._typing_core import BoundsTuple
15 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
16 from pyvista.core.utilities.misc import _check_range
17 from pyvista.core.utilities.misc import _NameMixin
18 from pyvista.core.utilities.misc import _NoNewAttrMixin
19
20 from .colors import Color
21 from .prop3d import _Prop3DMixin
22 from .themes import Theme
23 from .tools import FONTS
24
25 if TYPE_CHECKING:
26 from collections.abc import Sequence
27
28 from pyvista import Property
29 from pyvista.core._typing_core import VectorLike
30
31 from ._typing import ColorLike
32
33 HorizontalOptions = Literal['left', 'center', 'right']
34 VerticalOptions = Literal['bottom', 'center', 'top']
35
36
37 class CornerAnnotation(_NoNewAttrMixin, DisableVtkSnakeCase, _NameMixin, _vtk.vtkCornerAnnotation):
38 """Text annotation in four corners.
39
40 This is an annotation object that manages four text actors / mappers to provide
41 annotation in the four corners of a viewport.
42
43 Parameters
44 ----------
45 position : str | bool
46 Position of the text.
47
48 text : str
49 Text input.
50
51 prop : pyvista.TextProperty, optional
52 Text property.
53
54 linear_font_scale_factor : float, optional
55 Linear font scale factor.
56
57 name : str, optional
58 The name of this actor used when tracking on a plotter.
59
60 .. versionadded:: 0.45
61
62 Examples
63 --------
64 Create text annotation in four corners.
65
66 >>> from pyvista import CornerAnnotation
67 >>> text = CornerAnnotation(0, 'text')
68 >>> prop = text.prop
69
70 """
71
72 @_deprecate_positional_args(allowed=['position', 'text'])
73 def __init__( # noqa: PLR0917
74 self, position, text, prop=None, linear_font_scale_factor=None, name=None
75 ):
76 """Initialize a new text annotation descriptor."""
77 super().__init__()
78 self.set_text(position, text)
79 if prop is None:
80 self.prop = TextProperty()
81 if linear_font_scale_factor is not None:
82 self.linear_font_scale_factor = linear_font_scale_factor
83 self._name = name
84
85 def get_text(self, position):
86 """Get the text to be displayed for each corner.
87
88 Parameters
89 ----------
90 position : str | bool
91 Position of the text.
92
93 Returns
94 -------
95 str
96 Text to be displayed for each corner.
97
98 """
99 return self.GetText(position)
100
101 def set_text(self, position, text):
102 """Set the text to be displayed for each corner.
103
104 Parameters
105 ----------
106 position : str | bool
107 Position of the text.
108
109 text : str
110 Text to be displayed for each corner.
111
112 """
113 corner_mappings = {
114 'lower_left': self.LowerLeft,
115 'lower_right': self.LowerRight,
116 'upper_left': self.UpperLeft,
117 'upper_right': self.UpperRight,
118 'lower_edge': self.LowerEdge,
119 'upper_edge': self.UpperEdge,
120 'left_edge': self.LeftEdge,
121 'right_edge': self.RightEdge,
122 }
123 corner_mappings['ll'] = corner_mappings['lower_left']
124 corner_mappings['lr'] = corner_mappings['lower_right']
125 corner_mappings['ul'] = corner_mappings['upper_left']
126 corner_mappings['ur'] = corner_mappings['upper_right']
127 corner_mappings['top'] = corner_mappings['upper_edge']
128 corner_mappings['bottom'] = corner_mappings['lower_edge']
129 corner_mappings['right'] = corner_mappings['right_edge']
130 corner_mappings['r'] = corner_mappings['right_edge']
131 corner_mappings['left'] = corner_mappings['left_edge']
132 corner_mappings['l'] = corner_mappings['left_edge']
133 if isinstance(position, str):
134 position = corner_mappings[position]
135 elif position is True:
136 position = corner_mappings['upper_left']
137 self.SetText(position, text)
138
139 @property
140 def prop(self) -> TextProperty:
141 """Property of this actor.
142
143 Returns
144 -------
145 pyvista.TextProperty
146 Property of this actor.
147
148 """
149 return self.GetTextProperty()
150
151 @prop.setter
152 def prop(self, prop: TextProperty):
153 self.SetTextProperty(prop)
154
155 @property
156 def linear_font_scale_factor(self) -> float:
157 """Font scaling factors.
158
159 Returns
160 -------
161 float
162 Font scaling factors.
163
164 """
165 return self.GetLinearFontScaleFactor()
166
167 @linear_font_scale_factor.setter
168 def linear_font_scale_factor(self, factor: float):
169 self.SetLinearFontScaleFactor(factor)
170
171
172 class Text(_NoNewAttrMixin, DisableVtkSnakeCase, _NameMixin, _vtk.vtkTextActor):
173 r"""Define text by default theme.
174
175 Parameters
176 ----------
177 text : str, optional
178 Text string to be displayed.
179 "\n" is recognized as a carriage return/linefeed (line separator).
180 The characters must be in the UTF-8 encoding.
181
182 position : Sequence[float], optional
183 The position coordinate.
184
185 prop : pyvista.TextProperty, optional
186 The property of this actor.
187
188 name : str, optional
189 The name of this actor used when tracking on a plotter.
190
191 .. versionadded:: 0.45
192
193 Examples
194 --------
195 Create a text with text's property.
196
197 >>> from pyvista import Text
198 >>> text = Text()
199 >>> prop = text.prop
200
201 """
202
203 @_deprecate_positional_args(allowed=['text'])
204 def __init__( # noqa: PLR0917
205 self, text=None, position=None, prop=None, name=None
206 ):
207 """Initialize a new text descriptor."""
208 super().__init__()
209 if text is not None:
210 self.input = text
211 if position is not None:
212 self.position = position
213 if prop is None:
214 self.prop = TextProperty()
215 self._name = name
216
217 @property
218 def input(self):
219 r"""Text string to be displayed.
220
221 Returns
222 -------
223 str
224 Text string to be displayed.
225 "\n" is recognized as a carriage return/linefeed (line separator).
226 The characters must be in the UTF-8 encoding.
227
228 """
229 return self.GetInput()
230
231 @input.setter # noqa: A003
232 def input(self, text: str):
233 self.SetInput(text)
234
235 @property
236 def prop(self):
237 """Property of this actor.
238
239 Returns
240 -------
241 pyvista.TextProperty
242 Property of this actor.
243
244 """
245 return self.GetTextProperty()
246
247 @prop.setter
248 def prop(self, prop: TextProperty):
249 self.SetTextProperty(prop)
250
251 @property
252 def position(self):
253 """Position coordinate.
254
255 Returns
256 -------
257 Sequence[float]
258 Position coordinate.
259
260 """
261 return self.GetPosition()
262
263 @position.setter
264 def position(self, position: Sequence[float]):
265 self.SetPosition(position[0], position[1])
266
267
268 class Label(_Prop3DMixin, Text):
269 """2D label actor with a 3D position coordinate.
270
271 Unlike :class:`~pyvista.Text`, which uses 2D viewport coordinates to position text
272 in a plot, this class instead uses a 3D position coordinate. This class may be
273 positioned, oriented, and transformed in a manner similar to a 3D
274 :class:`~pyvista.Actor`.
275
276 In addition, this class supports an additional :attr:`relative_position` attribute.
277 In general, it is recommended to simply use :attr:`~pyvista.Prop3D.position` when positioning a
278 :class:`Label` by itself. However, if the position of the label depends on the
279 positioning of another actor, both :attr:`~pyvista.Prop3D.position` and
280 :attr:`relative_position` may be used together.
281 In these cases, the :attr:`~pyvista.Prop3D.position` of the label and actor
282 should be kept in-sync. See the examples below.
283
284 Parameters
285 ----------
286 text : str, optional
287 Text string to be displayed.
288
289 position : VectorLike[float]
290 Position of the text in XYZ coordinates.
291
292 relative_position : VectorLike[float]
293 Position of the text in XYZ coordinates relative to its :attr:`~pyvista.Prop3D.position`.
294
295 size : int
296 Size of the text label.
297
298 prop : pyvista.TextProperty, optional
299 The property of this actor.
300
301 name : str, optional
302 The name of this actor used when tracking on a plotter.
303
304 .. versionadded:: 0.45
305
306 See Also
307 --------
308 pyvista.Plotter.add_point_labels
309
310 Examples
311 --------
312 Create a label for a point of interest. Here we add a label to the tip of a cone.
313
314 >>> import pyvista as pv
315 >>> cone_dataset = pv.Cone()
316 >>> tip = (0.5, 0, 0)
317 >>> label = pv.Label('tip', position=tip)
318
319 Plot the mesh and label.
320
321 >>> pl = pv.Plotter()
322 >>> cone_actor = pl.add_mesh(cone_dataset)
323 >>> _ = pl.add_actor(label)
324 >>> pl.show()
325
326 The previous example set the label's position as the cone's tip explicitly.
327 However, this means that the two actors now have different positions.
328
329 >>> cone_actor.position
330 (0.0, 0.0, 0.0)
331 >>> label.position
332 (0.5, 0.0, 0.0)
333
334 And if we change the 3D orientation of the cone and label, the label is no longer
335 positioned at the tip.
336
337 >>> cone_actor.orientation = 0, 0, 90
338 >>> label.orientation = 0, 0, 90
339 >>>
340 >>> pl = pv.Plotter()
341 >>> _ = pl.add_actor(cone_actor)
342 >>> _ = pl.add_actor(label)
343 >>> pl.show()
344
345 This is because rotations by :class:`pyvista.Prop3D` are applied **before** the
346 actor is moved to its final position, and therefore the label's position is not
347 considered in the rotation. Hence, the final position of the label remains at
348 ``(0.5, 0.0, 0.0)`` as it did earlier, despite changing its orientation.
349
350 If we want the position of the label to have the same positioning *relative* to the
351 cone, we can instead set its :attr:`relative_position`.
352
353 First, reset the label's position to match the cone's position.
354
355 >>> label.position = cone_actor.position
356 >>> label.position
357 (0.0, 0.0, 0.0)
358
359 Now set its :attr:`relative_position` to the tip of the cone.
360
361 >>> label.relative_position = tip
362 >>> label.relative_position
363 (0.5, 0.0, 0.0)
364
365 Plot the results. The label is now correctly positioned at the tip of the cone.
366 This is because the :attr:`relative_position` is considered as part of the
367 rotation.
368
369 >>> pl = pv.Plotter()
370 >>> _ = pl.add_actor(cone_actor)
371 >>> _ = pl.add_actor(label)
372 >>> pl.show()
373
374 As long as the label and cone's :class:`pyvista.Prop3D` attributes are modified
375 together and synchronized, the label will remain at the tip of the cone.
376
377 Modify the position of the label and tip.
378
379 >>> cone_actor.position = (1.0, 2.0, 3.0)
380 >>> label.position = (1.0, 2.0, 3.0)
381 >>> pl = pv.Plotter()
382 >>> _ = pl.add_actor(cone_actor)
383 >>> _ = pl.add_actor(label)
384 >>> _ = pl.add_axes_at_origin()
385 >>> pl.show()
386
387 """
388
389 def __init__(
390 self,
391 text: str | None = None,
392 position: VectorLike[float] = (0.0, 0.0, 0.0),
393 relative_position: VectorLike[float] = (0.0, 0.0, 0.0),
394 *,
395 size: int = 50,
396 prop: Property | None = None,
397 name: str = 'Label',
398 ):
399 Text.__init__(self, text=text, prop=prop)
400 self.GetPositionCoordinate().SetCoordinateSystemToWorld()
401 self.SetTextScaleModeToNone() # Use font size to control size of text
402 self._name = name
403
404 _Prop3DMixin.__init__(self)
405 self.relative_position = relative_position
406 self.position = position
407 self.size = size
408
409 @property
410 def _label_position(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
411 """Position of the label in xyz space.
412
413 This is the "true" position of the label. Internally this is loosely
414 equal to :attr:`~pyvista.Prop3D.position` + :attr:`relative_position`.
415 """
416 return self.GetPositionCoordinate().GetValue()
417
418 @_label_position.setter
419 def _label_position(self, position: VectorLike[float]):
420 valid_position = _validation.validate_array3(position)
421 self.GetPositionCoordinate().SetValue(valid_position)
422
423 @property
424 def size(self) -> int: # numpydoc ignore=RT01
425 """Size of the text label.
426
427 Notes
428 -----
429 The text property's font size used to control the size of the label.
430
431 """
432 return self.prop.font_size
433
434 @size.setter
435 def size(self, size: int):
436 self.prop.font_size = size
437
438 @property
439 def relative_position(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
440 """Position of the label relative to its :attr:`~pyvista.Prop3D.position`."""
441 return tuple(self._relative_position.tolist())
442
443 @relative_position.setter
444 def relative_position(self, position: VectorLike[float]):
445 self._relative_position = _validation.validate_array3(position, dtype_out=float)
446 self._post_set_update()
447
448 def _post_set_update(self):
449 # Update the label's underlying text position
450 matrix4x4 = self._transformation_matrix
451 vector4 = (*self.relative_position, 1)
452 new_position = (matrix4x4 @ vector4)[:3]
453 self._label_position = new_position
454
455 def _get_bounds(self) -> BoundsTuple:
456 # Define its 3D position as its bounds
457 x, y, z = self._label_position
458 return BoundsTuple(x, x, y, y, z, z)
459
460
461 class TextProperty(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkTextProperty):
462 """Define text's property.
463
464 Parameters
465 ----------
466 theme : pyvista.plotting.themes.Theme, optional
467 Plot-specific theme.
468
469 color : pyvista.ColorLike, optional
470 Either a string, RGB list, or hex color string. For example:
471 ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
472 ``color='#FFFFFF'``. Color will be overridden if scalars are
473 specified.
474
475 font_family : str | None, optional
476 Font family or None.
477
478 orientation : float, optional
479 Text's orientation (in degrees).
480
481 font_size : int, optional
482 Font size.
483
484 font_file : str, optional
485 Font file path.
486
487 shadow : bool, optional
488 If enable the shadow.
489
490 justification_horizontal : str, optional
491 Text's horizontal justification.
492 Should be either "left", "center" or "right".
493
494 justification_vertical : str, optional
495 Text's vertical justification.
496 Should be either "bottom", "center" or "top".
497
498 italic : bool, default: False
499 Italicises title and bar labels.
500
501 bold : bool, default: True
502 Bolds title and bar labels.
503
504 background_color : pyvista.Color, optional
505 Background color of text.
506
507 background_opacity : pyvista.Color, optional
508 Background opacity of text.
509
510 Examples
511 --------
512 Create a text's property.
513
514 >>> from pyvista import TextProperty
515 >>> prop = TextProperty()
516 >>> prop.opacity = 0.5
517 >>> prop.background_color = 'b'
518 >>> prop.background_opacity = 0.5
519 >>> prop.show_frame = True
520 >>> prop.frame_color = 'b'
521 >>> prop.frame_width = 10
522 >>> prop.frame_color
523 Color(name='blue', hex='#0000ffff', opacity=255)
524
525 """
526
527 _theme = Theme()
528 _color_set = None
529 _background_color_set = None
530 _font_family = None
531
532 @_deprecate_positional_args(allowed=['theme'])
533 def __init__( # noqa: PLR0917
534 self,
535 theme=None,
536 color=None,
537 font_family=None,
538 orientation=None,
539 font_size=None,
540 font_file=None,
541 shadow: bool = False, # noqa: FBT001, FBT002
542 justification_horizontal=None,
543 justification_vertical=None,
544 italic: bool = False, # noqa: FBT001, FBT002
545 bold: bool = False, # noqa: FBT001, FBT002
546 background_color=None,
547 background_opacity=None,
548 ):
549 """Initialize text's property."""
550 super().__init__()
551 if theme is None:
552 # copy global theme to ensure local property theme is fixed
553 # after creation.
554 self._theme.load_theme(pv.global_theme)
555 else:
556 self._theme.load_theme(theme)
557 self.color = color
558 self.font_family = font_family
559 if orientation is not None:
560 self.orientation = orientation
561 if font_size is not None:
562 self.font_size = font_size
563 if font_file is not None:
564 self.set_font_file(font_file)
565 if shadow:
566 self.enable_shadow()
567 if justification_horizontal is not None:
568 self.justification_horizontal = justification_horizontal
569 if justification_vertical is not None:
570 self.justification_vertical = justification_vertical
571 self.italic = italic
572 self.bold = bold
573 if background_color is not None:
574 self.background_color = background_color
575 if background_opacity is not None:
576 self.background_opacity = background_opacity
577
578 @property
579 def color(self) -> Color:
580 """Color of text's property.
581
582 Returns
583 -------
584 pyvista.Color
585 Color of text's property.
586
587 """
588 return Color(self.GetColor())
589
590 @color.setter
591 def color(self, color: ColorLike):
592 self._color_set = color is not None
593 rgb_color = Color(color, default_color=self._theme.font.color)
594 self.SetColor(rgb_color.float_rgb)
595
596 @property
597 def opacity(self) -> float:
598 """Opacity of text's property.
599
600 Returns
601 -------
602 float
603 Opacity of the text. A single float value that will be applied globally
604 opacity of the text and uniformly applied everywhere. Between 0 and 1.
605
606 """
607 return self.GetOpacity()
608
609 @opacity.setter
610 def opacity(self, opacity: float):
611 _check_range(opacity, (0, 1), 'opacity')
612 self.SetOpacity(opacity)
613
614 @property
615 def background_color(self) -> Color:
616 """Background color of text's property.
617
618 Returns
619 -------
620 pyvista.Color
621 Background color of text's property.
622
623 """
624 return Color(self.GetBackgroundColor())
625
626 @background_color.setter
627 def background_color(self, color: ColorLike):
628 self._background_color_set = color is not None
629 rgb_color = Color(color)
630 self.SetBackgroundColor(rgb_color.float_rgb)
631
632 @property
633 def background_opacity(self) -> float:
634 """Background opacity of text's property.
635
636 Returns
637 -------
638 float
639 Background opacity of the text. A single float value that will be applied globally.
640 Background opacity of the text and uniformly applied everywhere. Between 0 and 1.
641
642 """
643 return self.GetBackgroundOpacity()
644
645 @background_opacity.setter
646 def background_opacity(self, opacity: float):
647 _check_range(opacity, (0, 1), 'background_opacity')
648 self.SetBackgroundOpacity(opacity)
649
650 @property
651 def show_frame(self) -> bool:
652 """Visibility of frame.
653
654 Returns
655 -------
656 bool:
657 If shows the frame.
658
659 """
660 return bool(self.GetFrame())
661
662 @show_frame.setter
663 def show_frame(self, frame: bool):
664 self.SetFrame(frame)
665
666 @property
667 def frame_color(self) -> Color:
668 """Frame color of text property.
669
670 Returns
671 -------
672 pyvista.Color
673 Frame color of text property.
674
675 """
676 return Color(self.GetFrameColor())
677
678 @frame_color.setter
679 def frame_color(self, color):
680 self.SetFrameColor(Color(color).float_rgb)
681
682 @property
683 def frame_width(self) -> int:
684 """Width of the frame.
685
686 Returns
687 -------
688 int
689 Width of the frame. The width is expressed in pixels.
690 The default is 1 pixel.
691
692 """
693 return self.GetFrameWidth()
694
695 @frame_width.setter
696 def frame_width(self, width: int):
697 self.SetFrameWidth(width)
698
699 @property
700 def font_family(self) -> str | None:
701 """Font family.
702
703 Returns
704 -------
705 output : str | None
706 Font family or None.
707
708 """
709 return self._font_family
710
711 @font_family.setter
712 def font_family(self, font_family: str | None):
713 if font_family is None:
714 font_family = self._theme.font.family
715 self._font_family = font_family
716 self.SetFontFamily(FONTS[self._font_family].value)
717
718 @property
719 def font_size(self) -> int:
720 """Font size.
721
722 Returns
723 -------
724 int
725 Font size.
726
727 """
728 return self.GetFontSize()
729
730 @font_size.setter
731 def font_size(self, font_size: int):
732 self.SetFontSize(font_size)
733
734 def enable_shadow(self) -> None:
735 """Enable the shadow."""
736 self.SetShadow(True)
737
738 @property
739 def orientation(self) -> float:
740 """Text's orientation (in degrees).
741
742 Returns
743 -------
744 float
745 Text's orientation (in degrees).
746
747 """
748 return self.GetOrientation()
749
750 @orientation.setter
751 def orientation(self, orientation: float):
752 self.SetOrientation(orientation)
753
754 def set_font_file(self, font_file: str):
755 """Set the font file.
756
757 Parameters
758 ----------
759 font_file : str
760 Font file path.
761
762 """
763 path = pathlib.Path(font_file)
764 path = path.resolve()
765 if not Path(path).is_file():
766 msg = f'Unable to locate {path}'
767 raise FileNotFoundError(msg)
768 self.SetFontFamily(_vtk.VTK_FONT_FILE)
769 self.SetFontFile(str(path))
770
771 @property
772 def justification_horizontal(self) -> str:
773 """Text's justification horizontal.
774
775 Returns
776 -------
777 str
778 Text's horizontal justification.
779 Should be either "left", "center" or "right".
780
781 """
782 justification = self.GetJustificationAsString().lower()
783 if justification == 'centered':
784 justification = 'center'
785 return justification
786
787 @justification_horizontal.setter
788 def justification_horizontal(self, justification: str):
789 if justification.lower() == 'left':
790 self.SetJustificationToLeft()
791 elif justification.lower() == 'center':
792 self.SetJustificationToCentered()
793 elif justification.lower() == 'right':
794 self.SetJustificationToRight()
795 else:
796 msg = (
797 f'Invalid {justification} for justification_horizontal. '
798 'Should be either "left", "center" or "right".'
799 )
800 raise ValueError(msg)
801
802 @property
803 def justification_vertical(self) -> str:
804 """Text's vertical justification.
805
806 Returns
807 -------
808 str
809 Text's vertical justification.
810 Should be either "bottom", "center" or "top".
811
812 """
813 justification = self.GetVerticalJustificationAsString().lower()
814 if justification == 'centered':
815 justification = 'center'
816 return justification
817
818 @justification_vertical.setter
819 def justification_vertical(self, justification: str):
820 if justification.lower() == 'bottom':
821 self.SetVerticalJustificationToBottom()
822 elif justification.lower() == 'center':
823 self.SetVerticalJustificationToCentered()
824 elif justification.lower() == 'top':
825 self.SetVerticalJustificationToTop()
826 else:
827 msg = (
828 f'Invalid {justification} for justification_vertical. '
829 'Should be either "bottom", "center" or "top".'
830 )
831 raise ValueError(msg)
832
833 @property
834 def italic(self) -> bool:
835 """Italic of text's property.
836
837 Returns
838 -------
839 bool
840 If text is italic.
841
842 """
843 return bool(self.GetItalic())
844
845 @italic.setter
846 def italic(self, italic: bool):
847 self.SetItalic(italic)
848
849 @property
850 def bold(self) -> bool:
851 """Bold of text's property.
852
853 Returns
854 -------
855 bool
856 If text is bold.
857
858 """
859 return bool(self.GetBold())
860
861 @bold.setter
862 def bold(self, bold: bool):
863 self.SetBold(bold)
864
865 def shallow_copy(self, to_copy: TextProperty) -> None:
866 """Create a shallow copy of the text's property.
867
868 Parameters
869 ----------
870 to_copy : pyvista.TextProperty
871 Text's property to copy from.
872
873 """
874 self.ShallowCopy(to_copy)