Debian Codegraph @

pyvista/plotting/scalar_bars.py

raw
1 """PyVista Scalar bar module."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import weakref
7
8 import numpy as np
9
10 import pyvista as pv
11 from pyvista import MAX_N_COLOR_BARS
12 from pyvista import _vtk
13 from pyvista._deprecate_positional_args import _deprecate_positional_args
14 from pyvista.core.utilities.misc import _NoNewAttrMixin
15
16 from .colors import Color
17 from .tools import parse_font_family
18
19
20 class ScalarBars(_NoNewAttrMixin):
21 """Plotter Scalar Bars.
22
23 Parameters
24 ----------
25 plotter : pyvista.Plotter
26 Plotter that the scalar bars are associated with.
27
28 """
29
30 def __init__(self, plotter):
31 """Initialize ScalarBars."""
32 self._plotter = weakref.proxy(plotter)
33 self._scalar_bar_ranges = {}
34 self._scalar_bar_mappers = {}
35 self._scalar_bar_actors = {}
36 self._scalar_bar_widgets = {}
37
38 def clear(self):
39 """Remove all scalar bars and resets all scalar bar properties."""
40 self._scalar_bar_ranges = {}
41 self._scalar_bar_mappers = {}
42 self._scalar_bar_actors = {}
43 self._scalar_bar_widgets = {}
44
45 def __plotter_close__(self) -> None:
46 """Release scalar-bar state when the owning plotter closes."""
47 self.clear()
48
49 def __repr__(self):
50 """Nice representation of this class."""
51 lines = []
52 lines.append('Scalar Bar Title Interactive')
53 for title in self._scalar_bar_actors:
54 interactive = title in self._scalar_bar_widgets
55 title_quotes = f'"{title}"'
56 lines.append(f'{title_quotes:20} {interactive!s:5}')
57 return '\n'.join(lines)
58
59 @_deprecate_positional_args(allowed=['actor'])
60 def _remove_mapper_from_plotter(
61 self,
62 actor,
63 reset_camera: bool = False, # noqa: FBT001, FBT002
64 render: bool = False, # noqa: FBT001, FBT002
65 ): # numpydoc ignore=PR01,RT01
66 """Remove an actor's mapper from the given plotter's _scalar_bar_mappers.
67
68 This ensures that when actors are removed, their corresponding
69 scalar bars are removed.
70
71 """
72 try:
73 mapper = actor.GetMapper()
74 except AttributeError:
75 return
76
77 # NOTE: keys to list to prevent iterator changing during loop
78 for name in list(self._scalar_bar_mappers):
79 with contextlib.suppress(ValueError):
80 self._scalar_bar_mappers[name].remove(mapper)
81
82 if not self._scalar_bar_mappers[name]:
83 slot = self._plotter._scalar_bar_slot_lookup.pop(name, None)
84 if slot is not None:
85 self._scalar_bar_mappers.pop(name)
86 self._scalar_bar_ranges.pop(name)
87 self._plotter.remove_actor(
88 self._scalar_bar_actors.pop(name),
89 reset_camera=reset_camera,
90 render=render,
91 )
92 self._plotter._scalar_bar_slots.add(slot)
93 return
94
95 @_deprecate_positional_args(allowed=['title'])
96 def remove_scalar_bar(self, title=None, render: bool = True): # noqa: FBT001, FBT002
97 """Remove a scalar bar.
98
99 Parameters
100 ----------
101 title : str, optional
102 Title of the scalar bar to remove. Required if there is
103 more than one scalar bar.
104
105 render : bool, default: True
106 Render upon scalar bar removal. Set this to ``False`` to
107 stop the render window from rendering when a scalar bar
108 is removed.
109
110 Examples
111 --------
112 Remove a scalar bar from a plotter.
113
114 >>> import pyvista as pv
115 >>> mesh = pv.Sphere()
116 >>> mesh['data'] = mesh.points[:, 2]
117 >>> pl = pv.Plotter()
118 >>> _ = pl.add_mesh(mesh, cmap='coolwarm')
119 >>> pl.remove_scalar_bar()
120 >>> pl.show()
121
122 """
123 if title is None:
124 if len(self) > 1:
125 titles = ', '.join(f'"{key}"' for key in self._scalar_bar_actors)
126 msg = (
127 'Multiple scalar bars found. Pick title of the'
128 f'scalar bar from one of the following:\n{titles}'
129 )
130 raise ValueError(msg)
131 else:
132 title = next(iter(self._scalar_bar_actors.keys()))
133
134 actor = self._scalar_bar_actors.pop(title)
135 self._plotter.remove_actor(actor, render=render)
136 self._scalar_bar_ranges.pop(title)
137 self._scalar_bar_mappers.pop(title)
138
139 # add back in the scalar bar slot
140 slot = self._plotter._scalar_bar_slot_lookup.pop(title, None)
141 if slot is not None:
142 self._plotter._scalar_bar_slots.add(slot)
143
144 widget = self._scalar_bar_widgets.pop(title, None)
145 if widget is not None:
146 widget.SetEnabled(0)
147
148 def __len__(self):
149 """Return the number of scalar bar actors."""
150 return len(self._scalar_bar_actors)
151
152 def __getitem__(self, index):
153 """Return a scalar bar actor."""
154 return self._scalar_bar_actors[index]
155
156 def keys(self): # numpydoc ignore=RT01
157 """Scalar bar keys."""
158 return self._scalar_bar_actors.keys()
159
160 def values(self): # numpydoc ignore=RT01
161 """Scalar bar values."""
162 return self._scalar_bar_actors.values()
163
164 def items(self): # numpydoc ignore=RT01
165 """Scalar bar items."""
166 return self._scalar_bar_actors.items()
167
168 def __contains__(self, key) -> bool:
169 """Check if a title is a valid actors."""
170 return key in self._scalar_bar_actors
171
172 def update_title(
173 self,
174 old_title: str,
175 new_title: str,
176 *,
177 render: bool = False,
178 ) -> None:
179 """Update the title of an existing scalar bar.
180
181 .. versionadded:: 0.48.0
182
183 Parameters
184 ----------
185 old_title : str
186 Current title of the scalar bar to update.
187
188 new_title : str
189 New title for the scalar bar.
190
191 render : bool, default: False
192 Force a render after updating the title.
193
194 Raises
195 ------
196 KeyError
197 If no scalar bar with ``old_title`` exists.
198
199 ValueError
200 If a scalar bar with ``new_title`` already exists.
201
202 Examples
203 --------
204 Update the title of a scalar bar.
205
206 >>> import pyvista as pv
207 >>> mesh = pv.Sphere()
208 >>> mesh['Data'] = mesh.points[:, 2]
209 >>> pl = pv.Plotter()
210 >>> _ = pl.add_mesh(mesh, scalars='Data')
211 >>> pl.scalar_bars.update_title('Data', 'Elevation')
212 >>> pl.show()
213
214 """
215 if old_title not in self._scalar_bar_actors:
216 msg = f'Scalar bar with title "{old_title}" not found.'
217 raise KeyError(msg)
218 if old_title != new_title and new_title in self._scalar_bar_actors:
219 msg = f'Scalar bar with title "{new_title}" already exists.'
220 raise ValueError(msg)
221
222 if old_title != new_title:
223 self._scalar_bar_actors[new_title] = self._scalar_bar_actors.pop(old_title)
224 self._scalar_bar_ranges[new_title] = self._scalar_bar_ranges.pop(old_title)
225 self._scalar_bar_mappers[new_title] = self._scalar_bar_mappers.pop(old_title)
226 if old_title in self._scalar_bar_widgets:
227 self._scalar_bar_widgets[new_title] = self._scalar_bar_widgets.pop(old_title)
228 slot = self._plotter._scalar_bar_slot_lookup.pop(old_title, None)
229 if slot is not None:
230 self._plotter._scalar_bar_slot_lookup[new_title] = slot
231
232 self._scalar_bar_actors[new_title].SetTitle(new_title)
233
234 if render:
235 self._plotter.render()
236
237 @_deprecate_positional_args(allowed=['title'])
238 def add_scalar_bar( # noqa: PLR0917
239 self,
240 title='',
241 mapper=None,
242 n_labels=5,
243 italic: bool = False, # noqa: FBT001, FBT002
244 bold: bool = False, # noqa: FBT001, FBT002
245 title_font_size=None,
246 label_font_size=None,
247 color=None,
248 font_family=None,
249 shadow: bool = False, # noqa: FBT001, FBT002
250 width=None,
251 height=None,
252 position_x=None,
253 position_y=None,
254 vertical=None,
255 interactive=None,
256 fmt=None,
257 use_opacity: bool = True, # noqa: FBT001, FBT002
258 outline: bool = False, # noqa: FBT001, FBT002
259 nan_annotation: bool = False, # noqa: FBT001, FBT002
260 below_label=None,
261 above_label=None,
262 background_color=None,
263 n_colors=None,
264 fill: bool = False, # noqa: FBT001, FBT002
265 render: bool = False, # noqa: FBT001, FBT002
266 theme=None,
267 unconstrained_font_size: bool = False, # noqa: FBT001, FBT002
268 unique_bar: bool = False, # noqa: FBT001, FBT002
269 ):
270 """Create scalar bar using the ranges as set by the last input mesh.
271
272 Parameters
273 ----------
274 title : str, default: ""
275 Title of the scalar bar. Default is rendered as an empty title.
276
277 mapper : :vtk:`vtkMapper`, optional
278 Mapper used for the scalar bar. Defaults to the last
279 mapper created by the plotter.
280
281 n_labels : int, default: 5
282 Number of labels to use for the scalar bar.
283
284 italic : bool, default: False
285 Italicises title and bar labels.
286
287 bold : bool, default: False
288 Bolds title and bar labels.
289
290 title_font_size : float, optional
291 Sets the size of the title font. Defaults to ``None`` and is sized
292 according to :attr:`pyvista.plotting.themes.Theme.font`.
293
294 label_font_size : float, optional
295 Sets the size of the title font. Defaults to ``None`` and is sized
296 according to :attr:`pyvista.plotting.themes.Theme.font`.
297
298 color : ColorLike, optional
299 Either a string, rgb list, or hex color string. Default
300 set by :attr:`pyvista.plotting.themes.Theme.font`. Can be
301 in one of the following formats:
302
303 * ``color='white'``
304 * ``color='w'``
305 * ``color=[1.0, 1.0, 1.0]``
306 * ``color='#FFFFFF'``
307
308 font_family : {'courier', 'times', 'arial'}
309 Font family. Default is set by
310 :attr:`pyvista.plotting.themes.Theme.font`.
311
312 shadow : bool, default: False
313 Adds a black shadow to the text.
314
315 width : float, optional
316 The percentage (0 to 1) width of the window for the colorbar.
317 Default set by
318 :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
319 :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
320 depending on the value of ``vertical``.
321
322 height : float, optional
323 The percentage (0 to 1) height of the window for the
324 colorbar. Default set by
325 :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
326 :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
327 depending on the value of ``vertical``.
328
329 position_x : float, optional
330 The percentage (0 to 1) along the windows's horizontal
331 direction to place the bottom left corner of the colorbar.
332 Default set by
333 :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
334 :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
335 depending on the value of ``vertical``.
336
337 position_y : float, optional
338 The percentage (0 to 1) along the windows's vertical
339 direction to place the bottom left corner of the colorbar.
340 Default set by
341 :attr:`pyvista.plotting.themes.Theme.colorbar_vertical` or
342 :attr:`pyvista.plotting.themes.Theme.colorbar_horizontal`
343 depending on the value of ``vertical``.
344
345 vertical : bool, optional
346 Use vertical or horizontal scalar bar. Default set by
347 :attr:`pyvista.plotting.themes.Theme.colorbar_orientation`.
348
349 interactive : bool, optional
350 Use a widget to control the size and location of the scalar bar.
351 Default set by :attr:`pyvista.plotting.themes.Theme.interactive`.
352
353 fmt : str, optional
354 ``printf`` format for labels.
355 Default set by :attr:`pyvista.plotting.themes.Theme.font`.
356
357 use_opacity : bool, default: True
358 Optionally display the opacity mapping on the scalar bar.
359
360 outline : bool, default: False
361 Optionally outline the scalar bar to make opacity mappings more
362 obvious.
363
364 nan_annotation : bool, default: False
365 Annotate the NaN color.
366
367 below_label : str, optional
368 String annotation for values below the scalars range.
369
370 above_label : str, optional
371 String annotation for values above the scalars range.
372
373 background_color : ColorLike, optional
374 The color used for the background in RGB format.
375
376 n_colors : int, optional
377 The maximum number of color displayed in the scalar bar.
378
379 fill : bool, default: False
380 Draw a filled box behind the scalar bar with the
381 ``background_color``.
382
383 render : bool, default: False
384 Force a render when True.
385
386 theme : pyvista.plotting.themes.Theme, optional
387 Plot-specific theme. By default, calling from the
388 ``Plotter``, will use the plotter theme. Setting to
389 ``None`` will use the global theme.
390
391 unconstrained_font_size : bool, default: False
392 Whether the font size of title and labels is unconstrained.
393 When it is constrained, the size of the scalar bar will constrain the font size.
394 When it is not, the size of the font will always be respected.
395 Using custom labels will force this to be ``True``.
396
397 .. versionadded:: 0.44.0
398
399 unique_bar : bool, default: False
400 Whether to create a scalar bar which is unique to the subplot.
401 If ``True``, the scalar bar will be created with a unique key
402 which is not shared with other subplots, even if the input title is the same.
403
404 .. note::
405
406 Scalar bars are managed by a dictionary with the title
407 as the key. By default, if a scalar bar with the same title
408 already exists, the scalar bar will be shared.
409 If ``unique_bar`` is ``True``, the scalar bar will be created
410 with a unique key which is the title suffixed with
411 ``_UNIQUE_ID_{active_renderer_index}``, where ``active_renderer_index``
412 is the index of the active renderer in the plotter.
413 This allows for multiple scalar bars with the same title
414 to be created across different subplots.
415
416 .. versionadded:: 0.48.0
417
418 Returns
419 -------
420 :vtk:`vtkScalarBarActor`
421 Scalar bar actor.
422
423 Notes
424 -----
425 Setting ``title_font_size``, or ``label_font_size`` disables
426 automatic font sizing for both the title and label.
427
428 See Also
429 --------
430 :ref:`scalar_bar_example`
431
432 Examples
433 --------
434 Add a custom interactive scalar bar that is horizontal, has an
435 outline, and has a custom formatting.
436
437 >>> import pyvista as pv
438 >>> sphere = pv.Sphere()
439 >>> sphere['Data'] = sphere.points[:, 2]
440 >>> pl = pv.Plotter()
441 >>> _ = pl.add_mesh(sphere, show_scalar_bar=False)
442 >>> _ = pl.add_scalar_bar(
443 ... 'Data',
444 ... interactive=True,
445 ... vertical=False,
446 ... title_font_size=35,
447 ... label_font_size=30,
448 ... outline=True,
449 ... fmt='%10.5f',
450 ... )
451 >>> pl.show()
452
453 """
454 if mapper is None:
455 msg = 'Mapper cannot be ``None`` when creating a scalar bar'
456 raise ValueError(msg)
457
458 if theme is None:
459 theme = pv.global_theme
460
461 if interactive is None:
462 interactive = theme.interactive
463 if font_family is None:
464 font_family = theme.font.family
465 if label_font_size is None:
466 label_font_size = theme.font.label_size
467 if title_font_size is None:
468 title_font_size = theme.font.title_size
469 if fmt is None:
470 fmt = theme.font.fmt
471 if vertical is None and theme.colorbar_orientation.lower() == 'vertical':
472 vertical = True
473
474 # Automatically choose size if not specified
475 if width is None:
476 width = theme.colorbar_vertical.width if vertical else theme.colorbar_horizontal.width
477 if height is None:
478 if vertical:
479 height = theme.colorbar_vertical.height
480 else:
481 height = theme.colorbar_horizontal.height
482
483 display_title = title
484 if unique_bar:
485 title = f'{title}_UNIQUE_ID_{self._plotter.renderers.active_index}'
486
487 # Check that this data hasn't already been plotted
488 if title in list(self._scalar_bar_ranges.keys()):
489 clim = list(self._scalar_bar_ranges[title])
490 newrng = mapper.scalar_range
491 oldmappers = self._scalar_bar_mappers[title]
492 # get max for range and reset everything
493 clim[0] = min(newrng[0], clim[0])
494 clim[1] = max(newrng[1], clim[1])
495 for mh in oldmappers:
496 mh.scalar_range = clim[0], clim[1]
497 mapper.scalar_range = clim[0], clim[1]
498 self._scalar_bar_mappers[title].append(mapper)
499 self._scalar_bar_ranges[title] = clim
500 self._scalar_bar_actors[title].SetLookupTable(mapper.lookup_table)
501 # Color bar already present and ready to be used so returning
502 return None
503
504 # Automatically choose location if not specified
505 if position_x is None or position_y is None:
506 if not self._plotter._scalar_bar_slots:
507 msg = f'Maximum number of color bars ({MAX_N_COLOR_BARS}) reached.'
508 raise RuntimeError(msg)
509
510 slot = min(self._plotter._scalar_bar_slots)
511 self._plotter._scalar_bar_slots.remove(slot)
512 self._plotter._scalar_bar_slot_lookup[title] = slot
513
514 if position_x is None:
515 if vertical:
516 position_x = theme.colorbar_vertical.position_x
517 position_x -= slot * (width + 0.2 * width)
518 else:
519 position_x = theme.colorbar_horizontal.position_x
520
521 if position_y is None:
522 if vertical:
523 position_y = theme.colorbar_vertical.position_y
524 else:
525 position_y = theme.colorbar_horizontal.position_y
526 position_y += slot * height
527
528 # parse color
529 color = Color(color, default_color=theme.font.color)
530
531 # Create scalar bar
532 scalar_bar = _vtk.vtkScalarBarActor()
533 # self._scalar_bars.append(scalar_bar)
534
535 if background_color is not None:
536 background_color = np.array(Color(background_color).int_rgba)
537 scalar_bar.GetBackgroundProperty().SetColor(background_color[0:3])
538
539 if fill:
540 scalar_bar.DrawBackgroundOn()
541
542 lut = pv.LookupTable()
543 lut.DeepCopy(mapper.lookup_table)
544 ctable = _vtk.vtk_to_numpy(lut.GetTable())
545 alphas = ctable[:, -1][:, np.newaxis] / 255.0
546 use_table = ctable.copy()
547 use_table[:, -1] = 255.0
548 ctable = (use_table * alphas) + background_color * (1 - alphas)
549 lut.SetTable(_vtk.numpy_to_vtk(ctable, array_type=_vtk.VTK_UNSIGNED_CHAR))
550 else:
551 lut = mapper.lookup_table
552
553 scalar_bar.SetLookupTable(lut)
554 if n_colors is None:
555 # ensure the number of colors in the scalarbar's lookup table is at
556 # least the number in the mapper
557 n_colors = mapper.lookup_table.n_values
558
559 scalar_bar.SetMaximumNumberOfColors(n_colors)
560
561 if n_labels < 1:
562 scalar_bar.SetDrawTickLabels(False)
563 else:
564 scalar_bar.SetDrawTickLabels(True)
565 scalar_bar.SetNumberOfLabels(n_labels)
566
567 if nan_annotation:
568 scalar_bar.DrawNanAnnotationOn()
569
570 if above_label is not None:
571 scalar_bar.DrawAboveRangeSwatchOn()
572 scalar_bar.SetAboveRangeAnnotation(above_label)
573 elif lut.above_range_color:
574 scalar_bar.DrawAboveRangeSwatchOn()
575 scalar_bar.SetAboveRangeAnnotation('above')
576 if below_label is not None:
577 scalar_bar.DrawBelowRangeSwatchOn()
578 scalar_bar.SetBelowRangeAnnotation(below_label)
579 elif lut.below_range_color:
580 scalar_bar.DrawBelowRangeSwatchOn()
581 scalar_bar.SetBelowRangeAnnotation('below')
582
583 # edit the size of the colorbar
584 scalar_bar.SetHeight(height)
585 scalar_bar.SetWidth(width)
586 scalar_bar.SetPosition(position_x, position_y)
587
588 if fmt is not None:
589 scalar_bar.SetLabelFormat(fmt)
590
591 if vertical:
592 scalar_bar.SetOrientationToVertical()
593 else:
594 scalar_bar.SetOrientationToHorizontal()
595
596 if label_font_size is not None or title_font_size is not None:
597 scalar_bar.SetUnconstrainedFontSize(True)
598 scalar_bar.SetAnnotationTextScaling(False)
599 else:
600 scalar_bar.SetAnnotationTextScaling(True)
601
602 label_text = scalar_bar.GetLabelTextProperty()
603 anno_text = scalar_bar.GetAnnotationTextProperty()
604 label_text.SetColor(color.float_rgb)
605 anno_text.SetColor(color.float_rgb)
606 label_text.SetShadow(shadow)
607 anno_text.SetShadow(shadow)
608
609 # Set font
610 label_text.SetFontFamily(parse_font_family(font_family))
611 anno_text.SetFontFamily(parse_font_family(font_family))
612 label_text.SetItalic(italic)
613 anno_text.SetItalic(italic)
614 label_text.SetBold(bold)
615 anno_text.SetBold(bold)
616 if label_font_size:
617 label_text.SetFontSize(label_font_size)
618 anno_text.SetFontSize(label_font_size)
619
620 # Set properties
621 self._scalar_bar_ranges[title] = mapper.scalar_range
622 self._scalar_bar_mappers[title] = [mapper]
623
624 scalar_bar.SetTitle(display_title)
625 title_text = scalar_bar.GetTitleTextProperty()
626
627 title_text.SetJustificationToCentered()
628
629 title_text.SetItalic(italic)
630 title_text.SetBold(bold)
631 title_text.SetShadow(shadow)
632 if title_font_size:
633 title_text.SetFontSize(title_font_size)
634
635 # Set font
636 title_text.SetFontFamily(parse_font_family(font_family))
637
638 # set color
639 title_text.SetColor(color.float_rgb)
640
641 self._scalar_bar_actors[title] = scalar_bar
642 if interactive:
643 scalar_widget = _vtk.vtkScalarBarWidget()
644 scalar_widget.SetScalarBarActor(scalar_bar)
645 scalar_widget.SetInteractor(self._plotter.iren.interactor)
646 scalar_widget.SetEnabled(1)
647 rep = scalar_widget.GetRepresentation()
648
649 scalar_widget.On()
650 if vertical is True or vertical is None:
651 rep.SetOrientation(1) # type: ignore[attr-defined] # 0 = Horizontal, 1 = Vertical
652 else:
653 # y position determined empirically
654 y = -position_y / 2 - height - scalar_bar.GetPosition()[1]
655 rep.GetPositionCoordinate().SetValue(width, y) # type: ignore[attr-defined]
656 rep.GetPosition2Coordinate().SetValue(height, width) # type: ignore[attr-defined]
657 rep.SetOrientation(0) # type: ignore[attr-defined] # 0 = Horizontal, 1 = Vertical
658 self._scalar_bar_widgets[title] = scalar_widget
659
660 if use_opacity:
661 scalar_bar.SetUseOpacity(True)
662
663 if outline:
664 scalar_bar.SetDrawFrame(True)
665 frame_prop = scalar_bar.GetFrameProperty()
666 frame_prop.SetColor(color.float_rgb)
667 else:
668 scalar_bar.SetDrawFrame(False)
669
670 if unconstrained_font_size:
671 scalar_bar.SetUnconstrainedFontSize(True)
672
673 # finally, add to the actor and return the scalar bar
674 self._plotter.add_actor(scalar_bar, reset_camera=False, pickable=False, render=render)
675
676 return scalar_bar