Debian Codegraph @

pyvista/plotting/composite_mapper.py

raw
1 """Module containing composite data mapper."""
2
3 from __future__ import annotations
4
5 from itertools import cycle
6 import sys
7 from typing import TYPE_CHECKING
8 import weakref
9
10 import numpy as np
11
12 import pyvista as pv
13 from pyvista import _vtk
14 from pyvista import vtk_version_info
15 from pyvista._deprecate_positional_args import _deprecate_positional_args
16 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
17 from pyvista.core.utilities.arrays import convert_array
18 from pyvista.core.utilities.arrays import convert_string_array
19 from pyvista.core.utilities.misc import _check_range
20 from pyvista.core.utilities.misc import _NoNewAttrMixin
21
22 from .colors import Color
23 from .colors import get_cycler
24 from .mapper import _BaseMapper
25
26 if TYPE_CHECKING:
27 from collections.abc import Sequence
28
29 import cycler
30
31 from pyvista import MultiBlock
32
33 from ._typing import ColorLike
34
35
36 class BlockAttributes(_NoNewAttrMixin):
37 """Block attributes used to set the attributes of a block.
38
39 Parameters
40 ----------
41 block : pyvista.DataObject
42 PyVista data object.
43
44 attr : pyvista.plotting.composite_mapper.CompositeAttributes
45 Parent attributes.
46
47 Notes
48 -----
49 This class employs VTK's flat indexing and allows for accessing both
50 the blocks of a composite dataset as well as the entire composite
51 dataset. If there is only one composite dataset, ``A``, which contains
52 datasets ``[b, c]``, the indexing would be ``[A, b, c]``.
53
54 If there are two composite datasets ``[B, C]`` in one composite
55 dataset, ``A``, each of which containing three additional datasets
56 ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
57 ``A``, would be the zero index, followed by the first child, ``B``,
58 followed by all the children of ``B``, ``[d, e, f]``. In data
59 structures, this flat indexing would be known as "Depth-first search"
60 and the entire indexing would be::
61
62 [A, B, d, e, f, C, g, h, i]
63
64 Note how the composite datasets themselves are capitalized and are
65 accessible in the flat indexing, and not just the datasets.
66
67 Examples
68 --------
69 Add a sphere and a cube as a multiblock dataset to a plotter and then
70 change the visibility and color of the blocks. Note how the index of the
71 cube is ``1`` as the index of the entire multiblock is ``0``.
72
73 >>> import pyvista as pv
74 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
75 >>> pl = pv.Plotter()
76 >>> actor, mapper = pl.add_composite(dataset)
77 >>> mapper.block_attr[1].color = 'b'
78 >>> mapper.block_attr[1].opacity = 0.1
79 >>> mapper.block_attr[1]
80 Composite Block Addr=... Attributes
81 Visible: None
82 Opacity: 0.1
83 Color: Color(name='blue', hex='#0000ffff', opacity=255)
84 Pickable None
85
86 >>> pl.show()
87
88 """
89
90 def __init__(self, block, attr):
91 """Initialize the block attributes class."""
92 self._block = block
93 self.__attr = weakref.ref(attr)
94
95 @property
96 def _attr(self):
97 """Return the CompositeAttributes."""
98 return self.__attr()
99
100 @property
101 def _has_color(self):
102 """Return if a block has its color set."""
103 return self._attr.HasBlockColor(self._block)
104
105 @property
106 def _has_visibility(self):
107 """Return if a block has its visibility set."""
108 return self._attr.HasBlockVisibility(self._block)
109
110 @property
111 def _has_opacity(self):
112 """Return if a block has its opacity set."""
113 return self._attr.HasBlockOpacity(self._block)
114
115 @property
116 def _has_pickable(self):
117 """Return if a block has its pickability set."""
118 return self._attr.HasBlockPickability(self._block)
119
120 @property
121 def color(self): # numpydoc ignore=RT01
122 """Get or set the color of a block.
123
124 Examples
125 --------
126 Set the colors of a composite dataset to red and blue.
127
128 Note how the zero index is the entire multiblock, so we have to add 1
129 to our indexing to access the right block.
130
131 >>> import pyvista as pv
132 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
133 >>> pl = pv.Plotter()
134 >>> actor, mapper = pl.add_composite(dataset)
135 >>> mapper.block_attr[1].color = 'r'
136 >>> mapper.block_attr[2].color = 'b'
137 >>> pl.show()
138
139 """
140 if not self._has_color:
141 return None
142 return Color(tuple(self._attr.GetBlockColor(self._block)))
143
144 @color.setter
145 def color(self, new_color):
146 if new_color is None:
147 self._attr.RemoveBlockColor(self._block)
148 self._attr.Modified()
149 return
150 self._attr.SetBlockColor(self._block, Color(new_color).float_rgb)
151
152 @property
153 def visible(self) -> bool | None: # numpydoc ignore=RT01
154 """Get or set the visibility of a block.
155
156 Examples
157 --------
158 Hide the first block of a composite dataset.
159
160 Note how the zero index is the entire multiblock, so we have to add 1
161 to our indexing to access the right block.
162
163 >>> import pyvista as pv
164 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
165 >>> pl = pv.Plotter()
166 >>> actor, mapper = pl.add_composite(dataset)
167 >>> mapper.block_attr[1].visible = False
168 >>> pl.show()
169
170 """
171 if not self._has_visibility:
172 return None
173 return self._attr.GetBlockVisibility(self._block)
174
175 @visible.setter
176 def visible(self, new_visible: bool | None):
177 if new_visible is None:
178 self._attr.RemoveBlockVisibility(self._block)
179 self._attr.Modified()
180 return
181 self._attr.SetBlockVisibility(self._block, new_visible)
182
183 @property
184 def opacity(self) -> float | None: # numpydoc ignore=RT01
185 """Get or set the opacity of a block.
186
187 If opacity has not been set this will be ``None``.
188
189
190 Examples
191 --------
192 Change the opacity of the second block of the dataset.
193
194 Note how the zero index is the entire multiblock, so we have to add 1
195 to our indexing to access the right block.
196
197 >>> import pyvista as pv
198 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
199 >>> pl = pv.Plotter()
200 >>> actor, mapper = pl.add_composite(dataset)
201 >>> mapper.block_attr[2].opacity = 0.5
202 >>> pl.show()
203
204 """
205 if not self._has_opacity:
206 return None
207 return self._attr.GetBlockOpacity(self._block)
208
209 @opacity.setter
210 def opacity(self, new_opacity: float | None):
211 if new_opacity is None:
212 self._attr.RemoveBlockOpacity(self._block)
213 self._attr.Modified()
214 return
215
216 _check_range(new_opacity, (0, 1), 'opacity')
217 self._attr.SetBlockOpacity(self._block, new_opacity)
218
219 @property
220 def pickable(self) -> bool | None: # numpydoc ignore=RT01
221 """Get or set the pickability of a block.
222
223 Examples
224 --------
225 Make the cube of a multiblock dataset pickable and the sphere unpickable.
226
227 Note how the zero index is the entire multiblock, so we have to add 1
228 to our indexing to access the right block.
229
230 >>> import pyvista as pv
231 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
232 >>> pl = pv.Plotter()
233 >>> actor, mapper = pl.add_composite(dataset)
234 >>> mapper.block_attr[1].pickable = True
235 >>> mapper.block_attr[2].pickable = False
236 >>> pl.close()
237
238 See :ref:`composite_picking_example` for a full example using block
239 picking.
240
241 """
242 if not self._has_pickable:
243 return None
244 return self._attr.GetBlockPickability(self._block)
245
246 @pickable.setter
247 def pickable(self, new_pickable: bool | None):
248 if new_pickable is None:
249 self._attr.RemoveBlockPickability(self._block)
250 self._attr.Modified()
251 return
252 self._attr.SetBlockPickability(self._block, new_pickable)
253
254 def __repr__(self):
255 """Representation of block properties."""
256 return '\n'.join(
257 [
258 f'Composite Block {self._block.memory_address} Attributes',
259 f'Visible: {self.visible}',
260 f'Opacity: {self.opacity}',
261 f'Color: {self.color}',
262 f'Pickable {self.pickable}',
263 ],
264 )
265
266
267 class CompositeAttributes(
268 _NoNewAttrMixin,
269 DisableVtkSnakeCase,
270 _vtk.vtkCompositeDataDisplayAttributes,
271 ):
272 """Block attributes.
273
274 Parameters
275 ----------
276 mapper : pyvista.plotting.composite_mapper.CompositePolyDataMapper
277 Parent mapper.
278
279 dataset : pyvista.MultiBlock
280 Multiblock dataset.
281
282 Notes
283 -----
284 This class employs VTK's flat indexing and allows for accessing both
285 the blocks of a composite dataset as well as the entire composite
286 dataset. If there is only one composite dataset, ``A``, which contains
287 datasets ``[b, c]``, the indexing would be ``[A, b, c]``.
288
289 If there are two composite datasets ``[B, C]`` in one composite
290 dataset, ``A``, each of which containing three additional datasets
291 ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
292 ``A``, would be the zero index, followed by the first child, ``B``,
293 followed by all the children of ``B``, ``[d, e, f]``. In data
294 structures, this flat indexing would be known as "Depth-first search"
295 and the entire indexing would be::
296
297 [A, B, d, e, f, C, g, h, i]
298
299 Note how the composite datasets themselves are capitalized and are
300 accessible in the flat indexing, and not just the datasets.
301
302 Examples
303 --------
304 Add a sphere and a cube as a multiblock dataset to a plotter and then
305 change the visibility and color of the blocks. Note how the index of the
306 cube is ``1`` as the index of the entire multiblock is ``0``.
307
308 >>> import pyvista as pv
309 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
310 >>> pl = pv.Plotter()
311 >>> actor, mapper = pl.add_composite(dataset)
312 >>> mapper.block_attr[1].color = 'b'
313 >>> mapper.block_attr[1].opacity = 0.1
314 >>> mapper.block_attr[1]
315 Composite Block Addr=... Attributes
316 Visible: None
317 Opacity: 0.1
318 Color: Color(name='blue', hex='#0000ffff', opacity=255)
319 Pickable None
320
321 >>> pl.show()
322
323 """
324
325 def __init__(self, mapper, dataset):
326 """Initialize CompositeAttributes."""
327 super().__init__()
328 mapper.SetCompositeDataDisplayAttributes(self)
329 self._dataset = dataset
330
331 def reset_visibilities(self):
332 """Reset the visibility of all blocks.
333
334 Examples
335 --------
336 Hide the first block of a composite dataset and then show all by
337 resetting visibilities.
338
339 Note how the zero index is the entire multiblock, so we have to add 1
340 to our indexing to access the right block.
341
342 >>> import pyvista as pv
343 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
344 >>> pl = pv.Plotter()
345 >>> actor, mapper = pl.add_composite(dataset)
346 >>> mapper.block_attr[1].visible = False
347 >>> mapper.block_attr.reset_visibilities()
348 >>> pl.show()
349
350 """
351 self.RemoveBlockVisibilities()
352
353 def reset_pickabilities(self):
354 """Reset the pickability of all blocks.
355
356 Examples
357 --------
358 Make the cube of a multiblock dataset pickable and the sphere
359 unpickable, then reset it.
360
361 Note how the zero index is the entire multiblock, so we have to add 1
362 to our indexing to access the right block.
363
364 >>> import pyvista as pv
365 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
366 >>> pl = pv.Plotter()
367 >>> actor, mapper = pl.add_composite(dataset)
368 >>> mapper.block_attr[1].pickable = True
369 >>> mapper.block_attr[2].pickable = False
370 >>> mapper.block_attr.reset_pickabilities()
371 >>> [
372 ... mapper.block_attr[1].pickable,
373 ... mapper.block_attr[2].pickable,
374 ... ]
375 [None, None]
376 >>> pl.close()
377
378 """
379 self.RemoveBlockPickabilities()
380
381 def reset_colors(self):
382 """Reset the color of all blocks.
383
384 Examples
385 --------
386 Set individual block colors and then reset them.
387
388 >>> import pyvista as pv
389 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
390 >>> pl = pv.Plotter()
391 >>> actor, mapper = pl.add_composite(dataset, color='w')
392 >>> mapper.block_attr[1].color = 'r'
393 >>> mapper.block_attr[2].color = 'b'
394 >>> mapper.block_attr.reset_colors()
395 >>> pl.show()
396
397 """
398 self.RemoveBlockColors()
399
400 def reset_opacities(self):
401 """Reset the opacities of all blocks.
402
403 Examples
404 --------
405 Change the opacity of the second block of the dataset then reset all
406 opacities.
407
408 Note how the zero index is the entire multiblock, so we have to add 1
409 to our indexing to access the right block.
410
411 >>> import pyvista as pv
412 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
413 >>> pl = pv.Plotter()
414 >>> actor, mapper = pl.add_composite(dataset)
415 >>> mapper.block_attr[2].opacity = 0.5
416 >>> mapper.block_attr.reset_opacities()
417 >>> pl.show()
418
419 """
420 self.RemoveBlockOpacities()
421
422 def get_block(self, index):
423 """Return a block by its flat index.
424
425 Parameters
426 ----------
427 index : int
428 Flat index of the block to retrieve.
429
430 Returns
431 -------
432 pyvista.DataObject
433 PyVista data object.
434
435 Notes
436 -----
437 This method employs VTK's flat indexing and allows for accessing both
438 the blocks of a composite dataset as well as the entire composite
439 dataset. If there is only one composite dataset, ``A``, which contains
440 datasets ``[b, c]``, the indexing would be ``[A, b, c]``.
441
442 If there are two composite datasets ``[B, C]`` in one composite
443 dataset, ``A``, each of which containing three additional datasets
444 ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
445 ``A``, would be the zero index, followed by the first child, ``B``,
446 followed by all the children of ``B``, ``[d, e, f]``. In data
447 structures, this flat indexing would be known as "Depth-first search"
448 and the entire indexing would be::
449
450 [A, B, d, e, f, C, g, h, i]
451
452 Note how the composite datasets themselves are capitalized and are
453 accessible in the flat indexing, and not just the datasets.
454
455 Examples
456 --------
457 Add a composite dataset to a plotter and access its block attributes.
458 Note how the zero index is the entire multiblock and you can use ``1``
459 and ``2`` to access the individual sub-blocks.
460
461 >>> import pyvista as pv
462 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
463 >>> pl = pv.Plotter()
464 >>> actor, mapper = pl.add_composite(dataset)
465 >>> mapper.block_attr.get_block(0)
466 MultiBlock (...)
467 N Blocks: 2
468 X Bounds: -5.000e-01, 5.000e-01
469 Y Bounds: -5.000e-01, 5.000e-01
470 Z Bounds: -5.000e-01, 1.500e+00
471
472 Note this is the same as using ``__getitem__``
473
474 >>> mapper.block_attr[0]
475 Composite Block Addr=... Attributes
476 Visible: None
477 Opacity: None
478 Color: None
479 Pickable None
480
481 """
482 try:
483 block = self.DataObjectFromIndex(index, self._dataset)
484 except OverflowError:
485 msg = f'Invalid block key: {index}'
486 raise KeyError(msg) from None
487 if block is None and index > len(self) - 1:
488 msg = f'index {index} is out of bounds. There are only {len(self)} blocks.'
489 raise KeyError(msg) from None
490 return block
491
492 def __getitem__(self, index):
493 """Return a block attribute by its flat index."""
494 return BlockAttributes(self.get_block(index), self)
495
496 def __len__(self):
497 """Return the number of blocks in this dataset."""
498 from pyvista import MultiBlock # avoid circular # noqa: PLC0415
499
500 # start with 1 as there is always a composite dataset and this is the
501 # root of the tree
502 cc = 1
503 for dataset in self._dataset:
504 if isinstance(dataset, MultiBlock):
505 cc += len(dataset) + 1 # include the block itself
506 else:
507 cc += 1
508 return cc
509
510 def __iter__(self):
511 """Return an iterator of all the block attributes."""
512 for ii in range(len(self)):
513 yield self[ii]
514
515
516 class CompositePolyDataMapper(
517 _BaseMapper,
518 (
519 _vtk.vtkCompositePolyDataMapper # type: ignore[misc]
520 if vtk_version_info >= (9, 3)
521 else _vtk.vtkCompositePolyDataMapper2
522 ),
523 ):
524 """Composite PolyData mapper.
525
526 Parameters
527 ----------
528 dataset : pyvista.MultiBlock, optional
529 Multiblock dataset.
530
531 theme : pyvista.plotting.themes.Theme, optional
532 Plot-specific theme.
533
534 color_missing_with_nan : bool, optional
535 Color any missing values with the ``nan_color``. This is useful
536 when not all blocks of the composite dataset have the specified
537 ``scalars``.
538
539 interpolate_before_map : bool, optional
540 Enabling makes for a smoother scalars display. Default is
541 ``True``. When ``False``, OpenGL will interpolate the
542 mapped colors which can result is showing colors that are
543 not present in the color map.
544
545 """
546
547 @_deprecate_positional_args(allowed=['dataset'])
548 def __init__( # noqa: PLR0917
549 self,
550 dataset=None,
551 theme=None,
552 color_missing_with_nan=None,
553 interpolate_before_map=None,
554 ):
555 """Initialize this composite mapper."""
556 super().__init__(theme=theme)
557 # this must be added to set the color, opacity, and visibility of
558 # individual blocks
559 self._attr = CompositeAttributes(self, dataset)
560 self.dataset = dataset
561
562 if color_missing_with_nan is not None:
563 self.color_missing_with_nan = color_missing_with_nan
564 if interpolate_before_map is not None:
565 self.interpolate_before_map = interpolate_before_map
566
567 self._orig_scalars_name: str | None = None
568
569 @property
570 def dataset(self) -> MultiBlock: # numpydoc ignore=RT01
571 """Return the composite dataset assigned to this mapper.
572
573 Examples
574 --------
575 >>> import pyvista as pv
576 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
577 >>> pl = pv.Plotter()
578 >>> actor, mapper = pl.add_composite(dataset)
579 >>> mapper.dataset
580 MultiBlock (...)
581 N Blocks: 2
582 X Bounds: -5.000e-01, 5.000e-01
583 Y Bounds: -5.000e-01, 5.000e-01
584 Z Bounds: -5.000e-01, 1.500e+00
585
586 """
587 return self._dataset
588
589 @dataset.setter
590 def dataset(self, obj: MultiBlock):
591 self.SetInputDataObject(obj)
592 self._dataset = obj
593 self._attr._dataset = obj
594
595 @property
596 def block_attr(self) -> CompositeAttributes: # numpydoc ignore=RT01
597 """Return the block attributes.
598
599 Notes
600 -----
601 ``block_attr`` employs VTK's flat indexing and allows for accessing
602 both the blocks of a composite dataset as well as the entire composite
603 dataset. If there is only one composite dataset, ``A``, which contains
604 datasets ``[b, c]``, the indexing would be ``[A, b, c]``.
605
606 If there are two composite datasets ``[B, C]`` in one composite
607 dataset, ``A``, each of which containing three additional datasets
608 ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
609 ``A``, would be the zero index, followed by the first child, ``B``,
610 followed by all the children of ``B``, ``[d, e, f]``. In data
611 structures, this flat indexing would be known as "Depth-first search"
612 and the entire indexing would be::
613
614 [A, B, d, e, f, C, g, h, i]
615
616 Examples
617 --------
618 Add a sphere and a cube as a multiblock dataset to a plotter and then
619 change the visibility and color of the blocks.
620
621 >>> import pyvista as pv
622 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
623 >>> pl = pv.Plotter()
624 >>> actor, mapper = pl.add_composite(dataset)
625 >>> mapper.block_attr[1].color = 'b'
626 >>> mapper.block_attr[1].opacity = 0.1
627 >>> mapper.block_attr[1]
628 Composite Block Addr=... Attributes
629 Visible: None
630 Opacity: 0.1
631 Color: Color(name='blue', hex='#0000ffff', opacity=255)
632 Pickable None
633
634 """
635 return self._attr
636
637 @property
638 def color_missing_with_nan(self) -> bool: # numpydoc ignore=RT01
639 """Color missing arrays with the NaN color.
640
641 Examples
642 --------
643 Enable coloring missing values with NaN.
644
645 >>> import pyvista as pv
646 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
647 >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
648 >>> pl = pv.Plotter()
649 >>> actor, mapper = pl.add_composite(
650 ... dataset, scalars='data', show_scalar_bar=False
651 ... )
652 >>> pv.global_theme.nan_color = 'r'
653 >>> mapper.color_missing_with_nan = True
654 >>> pl.show()
655
656 """
657 return self.GetColorMissingArraysWithNanColor()
658
659 @color_missing_with_nan.setter
660 def color_missing_with_nan(self, value: bool):
661 self.SetColorMissingArraysWithNanColor(value)
662
663 def set_unique_colors(
664 self,
665 color_cycler: bool | str | cycler.Cycler[str, ColorLike] | Sequence[ColorLike] = True, # noqa: FBT001, FBT002
666 ):
667 """Set each block of the dataset to a unique color.
668
669 This uses ``matplotlib``'s color cycler by default.
670
671 When a custom color cycler, or a sequence of
672 color-like objects, is passed it sets the blocks
673 to the corresponding colors.
674
675 Parameters
676 ----------
677 color_cycler : bool | str | cycler.Cycler | sequence[ColorLike]
678 The sequence of colors to cycle through,
679 if ``True``, uses matplotlib cycler.
680
681 Examples
682 --------
683 Set each block of the composite dataset to a unique color.
684
685 >>> import pyvista as pv
686 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
687 >>> pl = pv.Plotter()
688 >>> actor, mapper = pl.add_composite(dataset)
689 >>> mapper.set_unique_colors()
690 >>> mapper.block_attr[1].color
691 Color(name='tab:orange', hex='#ff7f0eff', opacity=255)
692 >>> mapper.block_attr[2].color
693 Color(name='tab:green', hex='#2ca02cff', opacity=255)
694
695 >>> pl.show()
696
697 """
698 self.scalar_visibility = False
699
700 if isinstance(color_cycler, bool):
701 colors = cycle(get_cycler('matplotlib'))
702 else:
703 colors = cycle(get_cycler(color_cycler))
704
705 for attr in self.block_attr:
706 attr.color = next(colors)['color']
707
708 @_deprecate_positional_args(allowed=['scalars_name'])
709 def set_scalars( # noqa: PLR0917
710 self,
711 scalars_name,
712 preference,
713 component,
714 annotations,
715 rgb,
716 scalar_bar_args,
717 n_colors,
718 nan_color,
719 above_color,
720 below_color,
721 clim,
722 cmap,
723 flip_scalars,
724 log_scale,
725 ):
726 """Set the scalars of the mapper.
727
728 Parameters
729 ----------
730 scalars_name : str
731 Name of the scalars in the dataset. Must already exist in at least
732 of the blocks.
733
734 preference : str
735 For each block, when ``block.n_points == block.n_cells`` and
736 setting scalars, this parameter sets how the scalars will be mapped
737 to the mesh. Default ``'point'``, causes the scalars will be
738 associated with the mesh points. Can be either ``'point'`` or
739 ``'cell'``.
740
741 component : int
742 Set component of vector valued scalars to plot. Must be
743 nonnegative, if supplied. If ``None``, the magnitude of
744 the vector is plotted.
745
746 annotations : dict
747 Pass a dictionary of annotations. Keys are the float
748 values in the scalars range to annotate on the scalar bar
749 and the values are the string annotations.
750
751 rgb : bool
752 If the ``scalars_name`` corresponds to a 2 dimensional array, plot
753 those values as RGB(A) colors.
754
755 scalar_bar_args : dict
756 Dictionary of keyword arguments to pass when adding the
757 scalar bar to the scene. For options, see
758 :func:`pyvista.Plotter.add_scalar_bar`.
759
760 n_colors : int
761 Number of colors to use when displaying scalars.
762
763 nan_color : ColorLike
764 The color to use for all ``NaN`` values in the plotted
765 scalar array.
766
767 above_color : ColorLike
768 Solid color for values below the scalars range
769 (``clim``). This will automatically set the scalar bar
770 ``above_label`` to ``'above'``.
771
772 below_color : ColorLike
773 Solid color for values below the scalars range
774 (``clim``). This will automatically set the scalar bar
775 ``below_label`` to ``'below'``.
776
777 clim : Sequence
778 Color bar range for scalars. Defaults to minimum and
779 maximum of scalars array. Example: ``[-1, 2]``. ``rng``
780 is also an accepted alias for this.
781
782 cmap : str | list | pyvista.LookupTable
783 Name of the Matplotlib colormap to use when mapping the
784 ``scalars``. See available Matplotlib colormaps. Only applicable
785 for when displaying ``scalars``.
786 ``colormap`` is also an accepted alias for this. If
787 ``colorcet`` or ``cmocean`` are installed, their colormaps can be
788 specified by name.
789
790 You can also specify a list of colors to override an existing
791 colormap with a custom one. For example, to create a three color
792 colormap you might specify ``['green', 'red', 'blue']``.
793
794 This parameter also accepts a :class:`pyvista.LookupTable`. If this
795 is set, all parameters controlling the color map like ``n_colors``
796 will be ignored.
797 are installed, their colormaps can be specified by name.
798
799 flip_scalars : bool
800 Flip direction of cmap. Most colormaps allow ``*_r``
801 suffix to do this as well.
802
803 log_scale : bool
804 Use log scale when mapping data to colors. Scalars less
805 than zero are mapped to the smallest representable
806 positive float.
807
808 Returns
809 -------
810 dict
811 Dictionary of scalar bar arguments.
812
813 """
814 self._orig_scalars_name = scalars_name
815
816 field, scalars_name, dtype = self._dataset._activate_plotting_scalars(
817 scalars_name=scalars_name,
818 preference=preference,
819 component=component,
820 rgb=rgb,
821 )
822
823 self.scalar_visibility = True
824 if rgb:
825 self.color_mode = 'direct'
826 return scalar_bar_args
827 else:
828 self.scalar_map_mode = field.name.lower()
829
830 scalar_bar_args.setdefault('title', scalars_name)
831
832 if clim is None:
833 clim = self._dataset.get_data_range(scalars_name, allow_missing=True)
834 self.scalar_range = clim
835
836 if log_scale and clim[0] <= 0:
837 clim = [sys.float_info.min, clim[1]]
838
839 if isinstance(cmap, pv.LookupTable):
840 self.lookup_table = cmap
841 else:
842 if dtype == np.bool_:
843 cats = np.array([b'False', b'True'], dtype='|S5')
844 values = np.array([0, 1])
845 n_colors = 2
846 scalar_bar_args.setdefault('n_labels', 0)
847 self.lookup_table.SetAnnotations(convert_array(values), convert_string_array(cats))
848 clim = [-0.5, 1.5]
849
850 self.lookup_table.log_scale = log_scale
851
852 if isinstance(annotations, dict):
853 self.lookup_table.annotations = annotations
854
855 # self.lookup_table.SetNumberOfTableValues(n_colors)
856 if nan_color:
857 self.lookup_table.nan_color = nan_color
858 if above_color:
859 self.lookup_table.above_range_color = above_color
860 scalar_bar_args.setdefault('above_label', 'above')
861 if below_color:
862 self.lookup_table.below_range_color = below_color
863 scalar_bar_args.setdefault('below_label', 'below')
864
865 if cmap is None:
866 cmap = pv.global_theme.cmap if self._theme is None else self._theme.cmap
867
868 if cmap is not None:
869 self.lookup_table.apply_cmap(cmap, n_colors, flip=flip_scalars)
870 elif flip_scalars:
871 self.lookup_table.SetHueRange(0.0, 0.66667)
872 else:
873 self.lookup_table.SetHueRange(0.66667, 0.0)
874
875 return scalar_bar_args