Debian Codegraph @

pyvista/plotting/charts.py

raw
1 """Module containing pyvista wrappers for the vtk Charts API."""
2
3 from __future__ import annotations
4
5 from collections.abc import Sequence
6 from functools import wraps
7 import inspect
8 import itertools
9 import re
10 from typing import TYPE_CHECKING
11 from typing import ClassVar
12 import weakref
13
14 from matplotlib.backends.backend_agg import FigureCanvasAgg
15 import matplotlib.pyplot as plt
16 import numpy as np
17
18 import pyvista as pv
19 from pyvista import _vtk
20 from pyvista._deprecate_positional_args import _deprecate_positional_args
21 from pyvista._warn_external import warn_external
22 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
23 from pyvista.core.utilities.misc import _NoNewAttrMixin
24 from pyvista.core.utilities.misc import abstract_class
25
26 from .colors import COLOR_SCHEMES
27 from .colors import SCHEME_NAMES
28 from .colors import Color
29 from .colors import _formatted_color_synonyms
30 from .colors import _formatted_hex_colors
31
32 if TYPE_CHECKING:
33 from ._typing import Chart
34
35
36 # region Some metaclass wrapping magic
37 class _vtkWrapperMeta(type): # noqa: N801
38 def __init__(cls, clsname, bases, attrs) -> None:
39 # Restore the signature of classes inheriting from _vtkWrapper
40 # Based on https://stackoverflow.com/questions/49740290/call-from-metaclass-shadows-signature-of-init
41 sig = inspect.signature(cls.__init__) # type: ignore[misc]
42 params = list(sig.parameters.values())
43 params.insert(
44 len(params) - 1 if params[-1].kind == inspect.Parameter.VAR_KEYWORD else len(params),
45 inspect.Parameter('_wrap', inspect.Parameter.KEYWORD_ONLY, default=None),
46 )
47 cls.__signature__ = sig.replace(parameters=params[1:])
48 super().__init__(clsname, bases, attrs)
49
50 def __call__(cls, *args, _wrap=None, **kwargs):
51 obj = cls.__new__(cls, *args, **kwargs) # type: ignore[arg-type, var-annotated]
52 obj._wrapped = _wrap
53 obj.__init__(*args, **kwargs)
54 return obj
55
56
57 class _vtkWrapper(DisableVtkSnakeCase, metaclass=_vtkWrapperMeta): # noqa: N801
58 def __getattribute__(self, item):
59 unwrapped_attrs = ['_wrapped', '__class__', '__init__']
60 wrapped = super().__getattribute__('_wrapped')
61 if item in unwrapped_attrs or wrapped is None:
62 return super().__getattribute__(item)
63 else:
64 if item[0].islower():
65 return super().__getattribute__(item)
66 try:
67 return wrapped.__getattribute__(item)
68 except AttributeError:
69 return super().__getattribute__(item)
70
71 def __str__(self):
72 if self._wrapped is None:
73 return super().__str__()
74 else:
75 return 'Wrapped: ' + self._wrapped.__str__()
76
77
78 # endregion
79
80
81 # region Documentation substitution
82 @abstract_class
83 class DocSubs:
84 """Helper class to substitute the docstrings of the listed member functions or properties."""
85
86 # The substitutions to use for this (sub)class
87 _DOC_SUBS: dict[str, str] | None = None
88 # Internal dictionary to store registered member functions/properties and their
89 # (to be substituted) docs.
90 _DOC_STORE = {} # type: ignore[var-annotated] # noqa: RUF012
91 # Tag used to mark members that require docstring substitutions.
92 _DOC_TAG = ':DOC_SUBS:'
93
94 def __init_subclass__(cls, **kwargs) -> None:
95 """Initialize subclasses."""
96 # First substitute all members for this class (marked in a super class)
97 if cls._DOC_SUBS is not None:
98 subs = {**cls._DOC_SUBS}
99 if 'cls' not in subs:
100 subs['cls'] = cls.__name__
101 for member_name, (m, d) in cls._DOC_STORE.items():
102 if member_name not in cls.__dict__:
103 # If the member is not part of the subclass' __dict__, we have to generate a
104 # wrapping function or property and add it to the subclass' __dict__.
105 # Otherwise, the docstring of the superclass would be used for the
106 # substitutions.
107 mem_sub = cls._wrap_member(m)
108 mem_sub.__doc__ = d
109 setattr(cls, member_name, mem_sub)
110 # Get the member function/property and safely substitute its docstring.
111 member = getattr(cls, member_name)
112 member.__doc__ = (member.__doc__ or '').format(**subs)
113
114 # Secondly, register all members of this class that require substitutions in subclasses
115 # Create copy of registered members so far
116 # TODO: B010
117 setattr(cls, '_DOC_STORE', {**cls._DOC_STORE}) # noqa: B010
118 for member_name, member in cls.__dict__.items():
119 if member.__doc__ and member.__doc__.startswith(cls._DOC_TAG):
120 # New method/property to register in this class (denoting their docstring should be
121 # substituted in subsequent child classes).
122 cls._DOC_STORE[member_name] = (member, member.__doc__[len(cls._DOC_TAG) :])
123 # Overwrite original docstring to prevent doctest issues
124 member.__doc__ = """Docstring to be specialized in subclasses."""
125
126 @staticmethod
127 def _wrap_member(member):
128 if callable(member):
129
130 @wraps(member)
131 def mem_sub(*args, **kwargs):
132 return member(*args, **kwargs)
133
134 elif isinstance(member, property):
135 mem_sub = property(member.fget, member.fset, member.fdel) # type: ignore[assignment]
136 else:
137 msg = 'Members other than methods and properties are currently not supported.'
138 raise NotImplementedError(msg)
139 return mem_sub
140
141
142 def doc_subs(member): # numpydoc ignore=PR01,RT01
143 """Doc subs wrapper.
144
145 Only common attribute between methods and properties that we can
146 modify is __doc__, so use that to mark members that need doc
147 substitutions.
148 Still, only methods can be marked for doc substitution (as for
149 properties the docstring seems to be overwritten when specifying
150 setters or deleters), hence this decorator should be applied
151 before the property decorator.
152 """
153 # Ensure we are operating on a method
154 if not callable(member): # pragma: no cover
155 msg = '`member` must be a callable.'
156 raise TypeError(msg)
157
158 # Safeguard against None docstring when using -OO
159 existing_doc = member.__doc__ or ''
160 member.__doc__ = DocSubs._DOC_TAG + existing_doc
161
162 return member
163
164
165 # endregion
166
167
168 class Pen(_vtkWrapper, _vtk.vtkPen):
169 """Pythonic wrapper for a VTK Pen, used to draw lines.
170
171 Parameters
172 ----------
173 color : ColorLike, default: "k"
174 Color of the lines drawn using this pen. Any color parsable by
175 :class:`pyvista.Color` is allowed.
176
177 width : float, default: 1
178 Width of the lines drawn using this pen.
179
180 style : str, default: "-"
181 Style of the lines drawn using this pen. See
182 :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed
183 line styles.
184
185 Notes
186 -----
187 .. _pen_line_styles:
188
189 LINE_STYLES : dict
190 Dictionary containing all allowed line styles as its keys.
191
192 .. include:: ../pen_line_styles.rst
193
194 """
195
196 LINE_STYLES: ClassVar[
197 dict[str, dict[str, int | str]]
198 ] = { # descr is used in the documentation, set to None to hide it from the docs.
199 '': {'id': _vtk.vtkPen.NO_PEN, 'descr': 'Hidden'},
200 '-': {'id': _vtk.vtkPen.SOLID_LINE, 'descr': 'Solid'},
201 '--': {'id': _vtk.vtkPen.DASH_LINE, 'descr': 'Dashed'},
202 ':': {'id': _vtk.vtkPen.DOT_LINE, 'descr': 'Dotted'},
203 '-.': {'id': _vtk.vtkPen.DASH_DOT_LINE, 'descr': 'Dash-dot'},
204 '-..': {'id': _vtk.vtkPen.DASH_DOT_DOT_LINE, 'descr': 'Dash-dot-dot'},
205 }
206
207 def __init__(self, color='k', width=1, style='-') -> None:
208 """Initialize a new Pen instance."""
209 super().__init__()
210 self.color = color
211 self.width = width
212 self.style = style
213
214 @property
215 def color(self): # numpydoc ignore=RT01
216 """Return or set the pen's color.
217
218 Examples
219 --------
220 Set the pen's color to red.
221
222 .. pyvista-plot::
223 :force_static:
224
225 >>> import pyvista as pv
226 >>> chart = pv.Chart2D()
227 >>> plot = chart.line([0, 1, 2], [2, 1, 3])
228 >>> plot.pen.color = 'r'
229 >>> chart.show()
230
231 """
232 return self._color
233
234 @color.setter
235 def color(self, val) -> None:
236 self._color = Color(val, default_color='black')
237 self.SetColor(*self._color.int_rgba)
238
239 @property
240 def width(self): # numpydoc ignore=RT01
241 """Return or set the pen's width.
242
243 Examples
244 --------
245 Set the pen's width to 10
246
247 .. pyvista-plot::
248 :force_static:
249
250 >>> import pyvista as pv
251 >>> chart = pv.Chart2D()
252 >>> plot = chart.line([0, 1, 2], [2, 1, 3])
253 >>> plot.pen.width = 10
254 >>> chart.show()
255
256 """
257 return self.GetWidth()
258
259 @width.setter
260 def width(self, val) -> None:
261 self.SetWidth(float(val))
262
263 @property
264 def style(self): # numpydoc ignore=RT01
265 """Return or set the pen's line style.
266
267 See :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed line styles.
268
269 Examples
270 --------
271 .. pyvista-plot::
272 :force_static:
273
274 >>> import pyvista as pv
275 >>> chart = pv.Chart2D()
276 >>> plot = chart.line([0, 1, 2], [2, 1, 3])
277 >>> plot.pen.style = '-.'
278 >>> chart.show()
279
280 """
281 return self._line_style
282
283 @style.setter
284 def style(self, val):
285 if val is None:
286 val = ''
287 try:
288 self.SetLineType(self.LINE_STYLES[val]['id']) # type: ignore[arg-type]
289 self._line_style = val
290 except KeyError:
291 formatted_styles = '", "'.join(self.LINE_STYLES.keys())
292 msg = f'Invalid line style. Allowed line styles: "{formatted_styles}"'
293 raise ValueError(msg)
294
295
296 class Brush(_vtkWrapper, _vtk.vtkBrush):
297 """Pythonic wrapper for a VTK Brush, used to fill shapes.
298
299 Parameters
300 ----------
301 color : ColorLike, default: "k"
302 Fill color of the shapes drawn using this brush. Any color
303 parsable by :class:`pyvista.Color` is allowed.
304
305 texture : pyvista.Texture, optional
306 Texture used to fill shapes drawn using this brush. Any object
307 convertible to a :class:`pyvista.Texture` is allowed. Defaults to
308 ``None``.
309
310 """
311
312 def __init__(self, color='k', texture=None) -> None:
313 """Initialize a new Pen instance."""
314 super().__init__()
315 self.color = color
316 self.texture = texture
317 self._interpolate = True # vtkBrush textureProperties defaults to LINEAR & STRETCH
318 self._repeat = False
319
320 @property
321 def color(self): # numpydoc ignore=RT01
322 """Return or set the brush's color.
323
324 Examples
325 --------
326 Set the brush's color to red.
327
328 .. pyvista-plot::
329 :force_static:
330
331 >>> import pyvista as pv
332 >>> chart = pv.Chart2D()
333 >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
334 >>> plot.brush.color = 'r'
335 >>> chart.show()
336
337 """
338 return self._color
339
340 @color.setter
341 def color(self, val) -> None:
342 self._color = Color(val, default_color='black')
343 self.SetColor(*self._color.int_rgba)
344
345 @property
346 def texture(self): # numpydoc ignore=RT01
347 """Return or set the brush's texture.
348
349 Examples
350 --------
351 Set the brush's texture to the sample puppy texture.
352
353 .. pyvista-plot::
354 :force_static:
355
356 >>> import pyvista as pv
357 >>> from pyvista import examples
358 >>> chart = pv.Chart2D()
359 >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
360 >>> plot.brush.texture = examples.download_puppy_texture()
361 >>> chart.show()
362
363 """
364 return self._texture
365
366 @texture.setter
367 def texture(self, val) -> None:
368 if val is None:
369 self._texture = None
370 self.SetTexture(None)
371 else:
372 self._texture = pv.Texture(val) # type: ignore[abstract]
373 self.SetTexture(self._texture.to_image())
374
375 @property
376 def texture_interpolate(self): # numpydoc ignore=RT01
377 """Set texture interpolation mode.
378
379 There are two modes:
380
381 * ``False`` - NEAREST
382 * ``True`` - LINEAR
383
384 Examples
385 --------
386 Set up a brush with a texture.
387
388 .. pyvista-plot::
389 :force_static:
390
391 >>> import pyvista as pv
392 >>> from pyvista import examples
393 >>> chart = pv.Chart2D()
394 >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
395 >>> plot.brush.texture = examples.download_puppy_texture()
396 >>> chart.show()
397
398 Disable linear interpolation.
399
400 >>> plot.brush.texture_interpolate = False
401 >>> chart.show()
402
403 """
404 return self._interpolate
405
406 @texture_interpolate.setter
407 def texture_interpolate(self, val) -> None:
408 self._interpolate = bool(val)
409 self._update_textureprops()
410
411 @property
412 def texture_repeat(self): # numpydoc ignore=RT01
413 """Return or set the texture repeat mode.
414
415 There are two modes:
416
417 * ``False`` - STRETCH
418 * ``True`` - REPEAT
419
420 Examples
421 --------
422 Set up a brush with a texture.
423
424 .. pyvista-plot::
425 :force_static:
426
427 >>> import pyvista as pv
428 >>> from pyvista import examples
429 >>> chart = pv.Chart2D()
430 >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
431 >>> plot.brush.texture = examples.download_puppy_texture()
432 >>> chart.show()
433
434 Enable texture repeat.
435
436 >>> plot.brush.texture_repeat = True
437 >>> chart.show()
438
439 """
440 return self._repeat
441
442 @texture_repeat.setter
443 def texture_repeat(self, val) -> None:
444 self._repeat = bool(val)
445 self._update_textureprops()
446
447 def _update_textureprops(self) -> None:
448 # Interpolation: NEAREST = 0x01, LINEAR = 0x02
449 # Stretch/repeat: STRETCH = 0x04, REPEAT = 0x08
450 self.SetTextureProperties(1 + int(self._interpolate) + 4 * (1 + int(self._repeat)))
451
452
453 class Axis(_vtkWrapper, _vtk.vtkAxis):
454 """Pythonic interface for a VTK Axis, used by 2D charts.
455
456 Parameters
457 ----------
458 label : str, default: ""
459 Axis label.
460
461 range : sequence[float], optional
462 Axis range, denoting the minimum and maximum values
463 displayed on this axis. Setting this to any valid value
464 other than ``None`` will change this axis behavior to
465 ``'fixed'``. Setting it to ``None`` will change the axis
466 behavior to ``'auto'``.
467
468 grid : bool, default: True
469 Flag to toggle grid lines visibility for this axis.
470
471 """
472
473 BEHAVIORS: ClassVar[dict[str, int]] = {'auto': _vtk.vtkAxis.AUTO, 'fixed': _vtk.vtkAxis.FIXED}
474
475 @_deprecate_positional_args
476 def __init__(self, label='', range=None, grid: bool = True) -> None: # noqa: A002, FBT001, FBT002
477 """Initialize a new Axis instance."""
478 super().__init__()
479 self._tick_locs = _vtk.vtkDoubleArray()
480 self._tick_labels = _vtk.vtkStringArray()
481 self._pen = Pen(color=(0, 0, 0))
482 self._grid_pen = Pen(color=(0.95, 0.95, 0.95))
483 self.SetPen(self._pen)
484 self.SetGridPen(self._grid_pen)
485 self.label = label
486 self._behavior = None # Will be set by specifying the range below
487 self.range = range
488 self.grid = grid
489
490 @property
491 def pen(self) -> Pen: # numpydoc ignore=RT01
492 """Pen used to draw the axis.
493
494 Examples
495 --------
496 Create a 2D chart and change the x-axis color to red with a width of 5.
497
498 .. pyvista-plot::
499 :force_static:
500
501 >>> import pyvista as pv
502 >>> chart = pv.Chart2D()
503 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
504 >>> chart.x_axis.pen.color = 'r'
505 >>> chart.x_axis.pen.width = 5
506 >>> chart.show()
507
508 """
509 return self._pen
510
511 @property
512 def grid_pen(self) -> Pen: # numpydoc ignore=RT01
513 """Pen used to draw the grid lines.
514
515 Examples
516 --------
517 Create a 2D chart and change the x-axis grid lines to a dashed style.
518
519 .. pyvista-plot::
520 :force_static:
521
522 >>> import pyvista as pv
523 >>> chart = pv.Chart2D()
524 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
525 >>> chart.x_axis.grid_pen.color = (0.5, 0.5, 0.5)
526 >>> chart.x_axis.grid_pen.style = '--'
527 >>> chart.show()
528
529 """
530 return self._grid_pen
531
532 @property
533 def label(self): # numpydoc ignore=RT01
534 """Return or set the axis label.
535
536 Examples
537 --------
538 Set the axis label to ``"Axis Label"``.
539
540 .. pyvista-plot::
541 :force_static:
542
543 >>> import pyvista as pv
544 >>> chart = pv.Chart2D()
545 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
546 >>> chart.x_axis.label = 'Axis Label'
547 >>> chart.show()
548
549 """
550 return self.GetTitle()
551
552 @label.setter
553 def label(self, val) -> None:
554 self.SetTitle(val)
555
556 @property
557 def label_visible(self): # numpydoc ignore=RT01
558 """Return or set the axis label's visibility.
559
560 Examples
561 --------
562 Hide the x-axis label of a 2D chart.
563
564 .. pyvista-plot::
565 :force_static:
566
567 >>> import pyvista as pv
568 >>> chart = pv.Chart2D()
569 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
570 >>> chart.x_axis.label_visible = False
571 >>> chart.show()
572
573 """
574 return self.GetTitleVisible()
575
576 @label_visible.setter
577 def label_visible(self, val) -> None:
578 self.SetTitleVisible(bool(val))
579
580 @property
581 def label_size(self): # numpydoc ignore=RT01
582 """Return or set the size of the axis label font.
583
584 Examples
585 --------
586 Set the x-axis label font size of a 2D chart to 20.
587
588 .. pyvista-plot::
589 :force_static:
590
591 >>> import pyvista as pv
592 >>> chart = pv.Chart2D()
593 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
594 >>> chart.x_axis.label_size = 20
595 >>> chart.x_axis.label_size
596 20
597 >>> chart.show()
598
599 """
600 return self.GetTitleProperties().GetFontSize()
601
602 @label_size.setter
603 def label_size(self, size) -> None:
604 self.GetTitleProperties().SetFontSize(size)
605
606 @property
607 def range(self): # numpydoc ignore=RT01
608 """Return or set the axis range.
609
610 This will automatically set the axis behavior to ``"fixed"``
611 when a valid range is given. Setting the range to ``None``
612 will set the axis behavior to ``"auto"``.
613
614 Examples
615 --------
616 Manually specify the x-axis range of a 2D chart.
617
618 .. pyvista-plot::
619 :force_static:
620
621 >>> import pyvista as pv
622 >>> chart = pv.Chart2D()
623 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
624 >>> chart.x_axis.range = [0, 5]
625 >>> chart.show()
626
627 Revert to automatic axis scaling.
628
629 >>> chart.x_axis.range = None
630 >>> chart.show()
631
632 """
633 r = [0.0, 0.0]
634 self.GetRange(r)
635 return r
636
637 @range.setter # noqa: A003
638 def range(self, val) -> None:
639 if val is None:
640 self.behavior = 'auto'
641 else:
642 self.behavior = 'fixed'
643 self.SetRange(*val)
644
645 @property
646 def behavior(self): # numpydoc ignore=RT01
647 """Set the axis' scaling behavior.
648
649 Allowed behaviors are ``'auto'`` to automatically rescale the
650 axis to fit all visible datapoints in the plot, or ``'fixed'``
651 to use the user defined range.
652
653 Examples
654 --------
655 Manually specify the x-axis range of a 2D chart.
656
657 .. pyvista-plot::
658 :force_static:
659
660 >>> import pyvista as pv
661 >>> chart = pv.Chart2D()
662 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
663 >>> chart.x_axis.range = [0, 5]
664 >>> chart.show()
665
666 Revert to automatic axis scaling.
667
668 >>> chart.x_axis.behavior = 'auto'
669 >>> chart.show()
670 >>> chart.x_axis.range
671 [0.0, 2.0]
672
673 """
674 return self._behavior
675
676 @behavior.setter
677 def behavior(self, val):
678 try:
679 self.SetBehavior(self.BEHAVIORS[val])
680 self._behavior = val
681 except KeyError:
682 formatted_behaviors = '", "'.join(self.BEHAVIORS.keys())
683 msg = f'Invalid behavior. Allowed behaviors: "{formatted_behaviors}"'
684 raise ValueError(msg)
685
686 @property
687 def margin(self): # numpydoc ignore=RT01
688 """Return or set the axis margin.
689
690 Examples
691 --------
692 Create a 2D chart.
693
694 .. pyvista-plot::
695 :force_static:
696
697 >>> import pyvista as pv
698 >>> chart = pv.Chart2D()
699 >>> chart.background_color = 'c'
700 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
701 >>> chart.show()
702
703 Manually specify a larger (bottom) margin for the x-axis and a
704 larger (left) margin for the y-axis.
705
706 >>> chart.x_axis.margin = 50
707 >>> chart.y_axis.margin = 50
708 >>> chart.show()
709
710 """
711 return self.GetMargins()[0]
712
713 @margin.setter
714 def margin(self, val) -> None:
715 # Second margin doesn't seem to have any effect? So we only expose the first entry as
716 # 'the margin'.
717 m = self.GetMargins()
718 self.SetMargins(val, m[1])
719
720 @property
721 def log_scale(self): # numpydoc ignore=RT01
722 """Flag denoting whether a log scale is used for this axis.
723
724 Note that setting this property to ``True`` will not guarantee
725 that the log scale will be enabled. Verify whether activating
726 the log scale succeeded by rereading this property.
727
728 Examples
729 --------
730 Create a 2D chart.
731
732 .. pyvista-plot::
733 :force_static:
734
735 >>> import pyvista as pv
736 >>> chart = pv.Chart2D()
737 >>> _ = chart.line([0, 1, 2, 3, 4], [1e0, 1e1, 1e2, 1e3, 1e4])
738 >>> chart.show()
739
740 Try to enable the log scale on the y-axis.
741
742 >>> chart.y_axis.log_scale = True
743 >>> chart.show()
744 >>> chart.y_axis.log_scale
745 True
746
747 """
748 return self.GetLogScaleActive()
749
750 @log_scale.setter
751 def log_scale(self, val) -> None:
752 # False: log_scale will be disabled
753 # True: axis will attempt to activate log_scale if possible
754 self.SetLogScale(bool(val))
755
756 @property
757 def grid(self): # numpydoc ignore=RT01
758 """Return or set the axis' grid line visibility.
759
760 Examples
761 --------
762 Create a 2D chart with grid lines disabled for the x-axis.
763
764 .. pyvista-plot::
765 :force_static:
766
767 >>> import pyvista as pv
768 >>> chart = pv.Chart2D()
769 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
770 >>> chart.x_axis.grid = False
771 >>> chart.show()
772
773 """
774 return self.GetGridVisible()
775
776 @grid.setter
777 def grid(self, val) -> None:
778 self.SetGridVisible(bool(val))
779
780 @property
781 def visible(self): # numpydoc ignore=RT01
782 """Return or set the axis' visibility.
783
784 Examples
785 --------
786 Create a 2D chart with no visible y-axis.
787
788 .. pyvista-plot::
789 :force_static:
790
791 >>> import pyvista as pv
792 >>> chart = pv.Chart2D()
793 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
794 >>> chart.y_axis.visible = False
795 >>> chart.show()
796
797 """
798 return self.GetAxisVisible()
799
800 @visible.setter
801 def visible(self, val) -> None:
802 self.SetAxisVisible(bool(val))
803
804 def toggle(self) -> None:
805 """Toggle the axis' visibility.
806
807 Examples
808 --------
809 Create a 2D chart.
810
811 .. pyvista-plot::
812 :force_static:
813
814 >>> import pyvista as pv
815 >>> chart = pv.Chart2D()
816 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
817 >>> chart.show()
818
819 Toggle the visibility of the y-axis.
820
821 >>> chart.y_axis.toggle()
822 >>> chart.show()
823
824 """
825 self.visible = not self.visible
826
827 # --- Ticks ---
828 @property
829 def tick_count(self): # numpydoc ignore=RT01
830 """Return or set the number of ticks drawn on this axis.
831
832 Setting this property to a negative value or ``None`` will
833 automatically determine the appropriate amount of ticks to
834 draw.
835
836 Examples
837 --------
838 Create a 2D chart with a reduced number of ticks on the x-axis.
839
840 .. pyvista-plot::
841 :force_static:
842
843 >>> import pyvista as pv
844 >>> chart = pv.Chart2D()
845 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
846 >>> chart.x_axis.tick_count = 5
847 >>> chart.show()
848
849 Revert back to automatic tick behavior.
850
851 >>> chart.x_axis.tick_count = None
852 >>> chart.show()
853
854 """
855 return self.GetNumberOfTicks()
856
857 @tick_count.setter
858 def tick_count(self, val) -> None:
859 if val is None or val < 0:
860 val = -1
861 self.SetNumberOfTicks(int(val))
862
863 @property
864 def tick_locations(self): # numpydoc ignore=RT01
865 """Return or set the tick locations for this axis.
866
867 Setting this to ``None`` will revert back to the default,
868 automatically determined, tick locations.
869
870 Examples
871 --------
872 Create a 2D chart with custom tick locations and labels on the y-axis.
873
874 .. pyvista-plot::
875 :force_static:
876
877 >>> import pyvista as pv
878 >>> chart = pv.Chart2D()
879 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
880 >>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
881 >>> chart.y_axis.tick_labels = [
882 ... 'Very small',
883 ... 'Small',
884 ... 'Still small',
885 ... 'Small?',
886 ... 'Not large',
887 ... 'Large?',
888 ... 'Very large',
889 ... ]
890 >>> chart.show()
891
892 Revert back to automatic tick placement.
893
894 >>> chart.y_axis.tick_locations = None
895 >>> chart.y_axis.tick_labels = None
896 >>> chart.show()
897
898 """
899 positions = self.GetTickPositions()
900 return tuple(positions.GetValue(i) for i in range(positions.GetNumberOfValues()))
901
902 @tick_locations.setter
903 def tick_locations(self, val) -> None:
904 self._tick_locs.Reset()
905 if val is not None:
906 for loc in val:
907 self._tick_locs.InsertNextValue(loc)
908 self._update_ticks()
909
910 @property
911 def tick_labels(self): # numpydoc ignore=RT01
912 """Return or set the tick labels for this axis.
913
914 You can specify a sequence, to provide a unique label to every
915 tick position; a string, to describe the label format to use
916 for each label; or ``None``, which will revert back to the
917 default tick labels. A label format is a string consisting of
918 an integer part, denoting the precision to use, and a final
919 character, denoting the notation to use.
920
921 Allowed notations:
922
923 * ``"f"`` for fixed notation
924 * ``"e"`` for scientific notation.
925
926 Examples
927 --------
928 Create a 2D chart with custom tick locations and labels on the y-axis.
929
930 .. pyvista-plot::
931 :force_static:
932
933 >>> import pyvista as pv
934 >>> chart = pv.Chart2D()
935 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
936 >>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
937 >>> chart.y_axis.tick_labels = [
938 ... 'Very small',
939 ... 'Small',
940 ... 'Still small',
941 ... 'Small?',
942 ... 'Not large',
943 ... 'Large?',
944 ... 'Very large',
945 ... ]
946 >>> chart.show()
947
948 Revert back to automatic tick placement.
949
950 >>> chart.y_axis.tick_locations = None
951 >>> chart.y_axis.tick_labels = None
952 >>> chart.show()
953
954 Specify a custom label format to use (fixed notation with precision 2).
955
956 >>> chart.y_axis.tick_labels = '2f'
957 >>> chart.show()
958
959 """
960 labels = self.GetTickLabels()
961 return tuple(labels.GetValue(i) for i in range(labels.GetNumberOfValues()))
962
963 @tick_labels.setter
964 def tick_labels(self, val) -> None:
965 self._tick_labels.Reset()
966 self.SetNotation(_vtk.vtkAxis.STANDARD_NOTATION)
967 if isinstance(val, str):
968 precision = int(val[:-1])
969 notation = val[-1].lower()
970 if notation == 'f':
971 self.SetNotation(_vtk.vtkAxis.FIXED_NOTATION)
972 self.SetPrecision(precision)
973 elif notation == 'e':
974 self.SetNotation(_vtk.vtkAxis.SCIENTIFIC_NOTATION)
975 self.SetPrecision(precision)
976 elif isinstance(val, Sequence):
977 for label in val:
978 self._tick_labels.InsertNextValue(label)
979 self._update_ticks()
980
981 @property
982 def tick_label_size(self): # numpydoc ignore=RT01
983 """Return or set the size of the axis tick label font.
984
985 Examples
986 --------
987 Set the x-axis tick label font size of a 2D chart to 20.
988
989 .. pyvista-plot::
990 :force_static:
991
992 >>> import pyvista as pv
993 >>> chart = pv.Chart2D()
994 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
995 >>> chart.x_axis.tick_label_size = 20
996 >>> chart.x_axis.tick_label_size
997 20
998 >>> chart.show()
999
1000 """
1001 return self.GetLabelProperties().GetFontSize()
1002
1003 @tick_label_size.setter
1004 def tick_label_size(self, size) -> None:
1005 self.GetLabelProperties().SetFontSize(size)
1006
1007 @property
1008 def tick_size(self): # numpydoc ignore=RT01
1009 """Return or set the size of this axis' ticks.
1010
1011 Examples
1012 --------
1013 Create a 2D chart with an x-axis with an increased tick size
1014 and adjusted offset for the tick labels.
1015
1016 .. pyvista-plot::
1017 :force_static:
1018
1019 >>> import pyvista as pv
1020 >>> chart = pv.Chart2D()
1021 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
1022 >>> chart.x_axis.tick_size += 10
1023 >>> chart.x_axis.tick_labels_offset += 12
1024 >>> chart.show()
1025
1026 """
1027 return self.GetTickLength()
1028
1029 @tick_size.setter
1030 def tick_size(self, val) -> None:
1031 self.SetTickLength(val)
1032
1033 @property
1034 def tick_labels_offset(self): # numpydoc ignore=RT01
1035 """Return or set the offset of the tick labels for this axis.
1036
1037 Examples
1038 --------
1039 Create a 2D chart with an x-axis with an increased tick size
1040 and adjusted offset for the tick labels.
1041
1042 .. pyvista-plot::
1043 :force_static:
1044
1045 >>> import pyvista as pv
1046 >>> chart = pv.Chart2D()
1047 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
1048 >>> chart.x_axis.tick_size += 10
1049 >>> chart.x_axis.tick_labels_offset += 12
1050 >>> chart.show()
1051
1052 """
1053 return self.GetLabelOffset()
1054
1055 @tick_labels_offset.setter
1056 def tick_labels_offset(self, val) -> None:
1057 self.SetLabelOffset(float(val))
1058
1059 @property
1060 def tick_labels_visible(self): # numpydoc ignore=RT01
1061 """Return or set the tick label visibility for this axis.
1062
1063 Examples
1064 --------
1065 Create a 2D chart with hidden tick labels on the y-axis.
1066
1067 .. pyvista-plot::
1068 :force_static:
1069
1070 >>> import pyvista as pv
1071 >>> chart = pv.Chart2D()
1072 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
1073 >>> chart.y_axis.tick_labels_visible = False
1074 >>> chart.show()
1075
1076 """
1077 return self.GetLabelsVisible()
1078
1079 @tick_labels_visible.setter
1080 def tick_labels_visible(self, val) -> None:
1081 self.SetLabelsVisible(bool(val))
1082 self.SetRangeLabelsVisible(bool(val))
1083
1084 @property
1085 def ticks_visible(self): # numpydoc ignore=RT01
1086 """Return or set the tick visibility for this axis.
1087
1088 Examples
1089 --------
1090 Create a 2D chart with hidden ticks on the y-axis.
1091
1092 .. pyvista-plot::
1093 :force_static:
1094
1095 >>> import pyvista as pv
1096 >>> chart = pv.Chart2D()
1097 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
1098 >>> chart.y_axis.ticks_visible = False
1099 >>> chart.show()
1100
1101 """
1102 return self.GetTicksVisible()
1103
1104 @ticks_visible.setter
1105 def ticks_visible(self, val) -> None:
1106 self.SetTicksVisible(bool(val))
1107
1108 def _update_ticks(self) -> None:
1109 locs = None if self._tick_locs.GetNumberOfValues() == 0 else self._tick_locs
1110 labels = None if self._tick_labels.GetNumberOfValues() == 0 else self._tick_labels
1111 self.SetCustomTickPositions(locs, labels)
1112
1113
1114 @abstract_class
1115 class _CustomContextItem(_vtk.vtkPythonItem):
1116 class ItemWrapper:
1117 def Initialize(self, item) -> bool: # noqa: ARG002, N802
1118 # item is the _CustomContextItem subclass instance
1119 return True
1120
1121 def Paint(self, item, painter): # noqa: N802
1122 # item is the _CustomContextItem subclass instance
1123 return item.paint(painter)
1124
1125 def __init__(self) -> None:
1126 super().__init__()
1127 # This will also call ItemWrapper.Initialize
1128 self.SetPythonObject(_CustomContextItem.ItemWrapper())
1129
1130 def paint(self, _) -> bool:
1131 return True
1132
1133
1134 class _ChartBackground(DisableVtkSnakeCase, _CustomContextItem):
1135 """Utility class for chart backgrounds."""
1136
1137 def __init__(self, chart) -> None:
1138 super().__init__()
1139 # Note: This SHOULD be a weakref proxy, as otherwise the garbage collector will not clean
1140 # up unused charts (because of the cyclic references between charts and their background).
1141 self._chart = weakref.proxy(chart) # Weakref proxy to the chart to draw the background for
1142 # Default background is translucent with black border line
1143 self.BorderPen = Pen(color=(0, 0, 0))
1144 self.BackgroundBrush = Brush(color=(0, 0, 0, 0))
1145 # Default active background is slightly more opaque with yellow border line
1146 self.ActiveBorderPen = Pen(color=(0.8, 0.8, 0.2))
1147 self.ActiveBackgroundBrush = Brush(color=(1.0, 1.0, 1.0, 0.4))
1148
1149 def paint(self, painter) -> bool:
1150 if self._chart.visible:
1151 painter.ApplyPen(self.ActiveBorderPen if self._chart._interactive else self.BorderPen)
1152 painter.ApplyBrush(
1153 self.ActiveBackgroundBrush if self._chart._interactive else self.BackgroundBrush,
1154 )
1155 l, b, w, h = self._chart._geometry
1156 painter.DrawRect(l, b, w, h)
1157 return True
1158
1159
1160 @abstract_class
1161 class _Chart(DocSubs):
1162 """Common interface for vtkChart, vtkChartBox, vtkChartPie, and ChartMPL instances."""
1163
1164 # Subclasses should specify following substitutions: 'chart_name', 'chart_args', 'chart_init'
1165 # and 'chart_set_labels'.
1166 _DOC_SUBS: dict[str, str] | None = None
1167
1168 def __init__(self, size=(1, 1), loc=(0, 0)) -> None:
1169 try:
1170 # Necessary for displaying charts, otherwise crashes on rendering
1171 # Import lazily on init to delay import until it's needed
1172 from vtkmodules import vtkRenderingContextOpenGL2 # noqa: F401, PLC0415, TID251
1173 except ImportError:
1174 msg = 'Unable to import `vtkRenderingContextOpenGL2`. Charts may not render.'
1175 warn_external(msg)
1176
1177 super().__init__()
1178 self._background = _ChartBackground(self)
1179 self._x_axis = Axis()
1180 self._y_axis = Axis()
1181 if size is not None:
1182 self.size = size
1183 if loc is not None:
1184 self.loc = loc
1185
1186 @property
1187 def _scene(self):
1188 """Get a reference to the :vtk:`vtkScene` in which this chart is drawn."""
1189 return self.GetScene() # type: ignore[attr-defined]
1190
1191 @property
1192 def _renderer(self):
1193 """Get a reference to the :vtk:`vtkRenderer` in which this chart is drawn."""
1194 return self._scene.GetRenderer() if self._scene is not None else None
1195
1196 def _render_event(self, *_, plotter_render: bool = False, **__) -> None:
1197 """Update the chart right before it will be rendered."""
1198 # Only resize on real VTK render events (plotter.render calls will afterwards invoke a
1199 # proper render event)
1200 if not plotter_render:
1201 self._resize()
1202
1203 def _resize(self):
1204 """Resize this chart.
1205
1206 Resize this chart such that it always occupies the specified
1207 geometry (matching the specified location and size).
1208
1209 Returns
1210 -------
1211 bool
1212 ``True`` if the chart was resized, ``False`` otherwise.
1213
1214 """
1215 # edge race case
1216 if self._renderer is None: # pragma: no cover
1217 return None
1218
1219 r_w, r_h = self._renderer.GetSize()
1220 # Alternatively: self.scene.GetViewWidth(), self.scene.GetViewHeight()
1221 _, _, c_w, c_h = (int(g) for g in self._geometry)
1222 # Target size is calculated from specified normalized width and height and the renderer's
1223 # current size
1224 t_w = int(self._size[0] * r_w)
1225 t_h = int(self._size[1] * r_h)
1226 resize = c_w != t_w or c_h != t_h
1227 if resize:
1228 # Mismatch between current size and target size, so resize chart:
1229 self._geometry = (int(self._loc[0] * r_w), int(self._loc[1] * r_h), t_w, t_h)
1230 return resize
1231
1232 @property
1233 def _geometry(self):
1234 """Chart geometry (x, y position of bottom left corner and width and height in pixels)."""
1235 return tuple(self.GetSize()) # type: ignore[attr-defined]
1236
1237 @_geometry.setter
1238 def _geometry(self, val) -> None:
1239 """Set the chart geometry."""
1240 self.SetSize(_vtk.vtkRectf(*val)) # type: ignore[attr-defined]
1241
1242 @property
1243 def _interactive(self):
1244 """Return or set the chart's interactivity.
1245
1246 Notes
1247 -----
1248 Users should not set this property directly, but use the
1249 :func:`Renderer.set_chart_interaction` method instead.
1250
1251 """
1252 return self.GetInteractive() # type: ignore[attr-defined]
1253
1254 @_interactive.setter
1255 def _interactive(self, val) -> None:
1256 self.SetInteractive(val) # type: ignore[attr-defined]
1257
1258 def _is_within(self, pos):
1259 """Check whether the specified position (in pixels) lies within this chart's geometry."""
1260 l, b, w, h = self._geometry
1261 return l <= pos[0] <= l + w and b <= pos[1] <= b + h
1262
1263 @property
1264 @doc_subs
1265 def size(self): # numpydoc ignore=RT01
1266 """Return or set the chart size in normalized coordinates.
1267
1268 A size of ``(1, 1)`` occupies the whole renderer.
1269
1270 Examples
1271 --------
1272 Create a half-sized {chart_name} centered in the middle of the
1273 renderer.
1274
1275 .. pyvista-plot::
1276 :force_static:
1277
1278 >>> import pyvista as pv
1279 >>> chart = pv.{cls}({chart_args}){chart_init}
1280 >>> chart.size = (0.5, 0.5)
1281 >>> chart.loc = (0.25, 0.25)
1282 >>> chart.show()
1283
1284 """
1285 return self._size
1286
1287 @size.setter
1288 def size(self, val):
1289 if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
1290 msg = f'Invalid size {val}.'
1291 raise ValueError(msg)
1292 self._size = val
1293
1294 @property
1295 @doc_subs
1296 def loc(self): # numpydoc ignore=RT01
1297 """Return or set the chart position in normalized coordinates.
1298
1299 This denotes the location of the chart's bottom left corner.
1300
1301 Examples
1302 --------
1303 Create a half-sized {chart_name} centered in the middle of the
1304 renderer.
1305
1306 .. pyvista-plot::
1307 :force_static:
1308
1309 >>> import pyvista as pv
1310 >>> chart = pv.{cls}({chart_args}){chart_init}
1311 >>> chart.size = (0.5, 0.5)
1312 >>> chart.loc = (0.25, 0.25)
1313 >>> chart.show()
1314
1315 """
1316 return self._loc
1317
1318 @loc.setter
1319 def loc(self, val):
1320 if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
1321 msg = f'Invalid loc {val}.'
1322 raise ValueError(msg)
1323 self._loc = val
1324
1325 @property
1326 @doc_subs
1327 def border_color(self): # numpydoc ignore=RT01
1328 """Return or set the chart's border color.
1329
1330 Examples
1331 --------
1332 Create a {chart_name} with a thick, dashed red border.
1333
1334 .. pyvista-plot::
1335 :force_static:
1336
1337 >>> import pyvista as pv
1338 >>> chart = pv.{cls}({chart_args}){chart_init}
1339 >>> chart.border_color = 'r'
1340 >>> chart.border_width = 5
1341 >>> chart.border_style = '--'
1342 >>> chart.show(interactive=False)
1343
1344 """
1345 return self._background.BorderPen.color
1346
1347 @border_color.setter
1348 def border_color(self, val) -> None:
1349 self._background.BorderPen.color = val
1350
1351 @property
1352 @doc_subs
1353 def border_width(self): # numpydoc ignore=RT01
1354 """Return or set the chart's border width.
1355
1356 Examples
1357 --------
1358 Create a {chart_name} with a thick, dashed red border.
1359
1360 .. pyvista-plot::
1361 :force_static:
1362
1363 >>> import pyvista as pv
1364 >>> chart = pv.{cls}({chart_args}){chart_init}
1365 >>> chart.border_color = 'r'
1366 >>> chart.border_width = 5
1367 >>> chart.border_style = '--'
1368 >>> chart.show(interactive=False)
1369
1370 """
1371 return self._background.BorderPen.width
1372
1373 @border_width.setter
1374 def border_width(self, val) -> None:
1375 self._background.BorderPen.width = val
1376 self._background.ActiveBorderPen.width = val
1377
1378 @property
1379 @doc_subs
1380 def border_style(self): # numpydoc ignore=RT01
1381 """Return or set the chart's border style.
1382
1383 Examples
1384 --------
1385 Create a {chart_name} with a thick, dashed red border.
1386
1387 .. pyvista-plot::
1388 :force_static:
1389
1390 >>> import pyvista as pv
1391 >>> chart = pv.{cls}({chart_args}){chart_init}
1392 >>> chart.border_color = 'r'
1393 >>> chart.border_width = 5
1394 >>> chart.border_style = '--'
1395 >>> chart.show(interactive=False)
1396
1397 """
1398 return self._background.BorderPen.style
1399
1400 @border_style.setter
1401 def border_style(self, val) -> None:
1402 self._background.BorderPen.style = val
1403 self._background.ActiveBorderPen.style = val
1404
1405 @property
1406 @doc_subs
1407 def active_border_color(self): # numpydoc ignore=RT01
1408 """Return or set the chart's border color in interactive mode.
1409
1410 Examples
1411 --------
1412 Create a {chart_name} with a thick, dashed red border.
1413
1414 .. pyvista-plot::
1415 :force_static:
1416
1417 >>> import pyvista as pv
1418 >>> chart = pv.{cls}({chart_args}){chart_init}
1419 >>> chart.border_color = 'r'
1420 >>> chart.border_width = 5
1421 >>> chart.border_style = '--'
1422 >>> chart.show(interactive=False)
1423
1424 Set the active border color to yellow and activate the chart.
1425
1426 >>> chart.active_border_color = 'y'
1427 >>> chart.show(interactive=True)
1428
1429 """
1430 return self._background.ActiveBorderPen.color
1431
1432 @active_border_color.setter
1433 def active_border_color(self, val) -> None:
1434 self._background.ActiveBorderPen.color = val
1435
1436 @property
1437 @doc_subs
1438 def background_color(self): # numpydoc ignore=RT01
1439 """Return or set the chart's background color.
1440
1441 Examples
1442 --------
1443 Create a {chart_name} with a green background.
1444
1445 .. pyvista-plot::
1446 :force_static:
1447
1448 >>> import pyvista as pv
1449 >>> chart = pv.{cls}({chart_args}){chart_init}
1450 >>> chart.background_color = (0.5, 0.9, 0.5)
1451 >>> chart.show(interactive=False)
1452
1453 """
1454 return self._background.BackgroundBrush.color
1455
1456 @background_color.setter
1457 def background_color(self, val) -> None:
1458 self._background.BackgroundBrush.color = val
1459
1460 @property
1461 @doc_subs
1462 def background_texture(self): # numpydoc ignore=RT01
1463 """Return or set the chart's background texture.
1464
1465 Examples
1466 --------
1467 Create a {chart_name} with an emoji as its background.
1468
1469 .. pyvista-plot::
1470 :force_static:
1471
1472 >>> import pyvista as pv
1473 >>> from pyvista import examples
1474 >>> chart = pv.{cls}({chart_args}){chart_init}
1475 >>> chart.background_texture = examples.download_emoji_texture()
1476 >>> chart.show(interactive=False)
1477
1478 """
1479 return self._background.BackgroundBrush.texture
1480
1481 @background_texture.setter
1482 def background_texture(self, val) -> None:
1483 self._background.BackgroundBrush.texture = val
1484 self._background.ActiveBackgroundBrush.texture = val
1485
1486 @property
1487 @doc_subs
1488 def active_background_color(self): # numpydoc ignore=RT01
1489 """Return or set the chart's background color in interactive mode.
1490
1491 Examples
1492 --------
1493 Create a {chart_name} with a green background.
1494
1495 .. pyvista-plot::
1496 :force_static:
1497
1498 >>> import pyvista as pv
1499 >>> chart = pv.{cls}({chart_args}){chart_init}
1500 >>> chart.background_color = (0.5, 0.9, 0.5)
1501 >>> chart.show(interactive=False)
1502
1503 Set the active background color to blue and activate the chart.
1504
1505 >>> chart.active_background_color = 'b'
1506 >>> chart.show(interactive=True)
1507
1508 """
1509 return self._background.ActiveBackgroundBrush.color
1510
1511 @active_background_color.setter
1512 def active_background_color(self, val) -> None:
1513 self._background.ActiveBackgroundBrush.color = val
1514
1515 @property
1516 @doc_subs
1517 def visible(self): # numpydoc ignore=RT01
1518 """Return or set the chart's visibility.
1519
1520 Examples
1521 --------
1522 Create a {chart_name}.
1523
1524 .. pyvista-plot::
1525 :force_static:
1526
1527 >>> import pyvista as pv
1528 >>> chart = pv.{cls}({chart_args}){chart_init}
1529 >>> chart.show()
1530
1531 Hide it.
1532
1533 >>> chart.visible = False
1534 >>> chart.show()
1535
1536 """
1537 return self.GetVisible() # type: ignore[attr-defined]
1538
1539 @visible.setter
1540 def visible(self, val) -> None:
1541 self.SetVisible(val) # type: ignore[attr-defined]
1542
1543 @doc_subs
1544 def toggle(self) -> None:
1545 """Toggle the chart's visibility.
1546
1547 Examples
1548 --------
1549 Create a {chart_name}.
1550
1551 .. pyvista-plot::
1552 :force_static:
1553
1554 >>> import pyvista as pv
1555 >>> chart = pv.{cls}({chart_args}){chart_init}
1556 >>> chart.show()
1557
1558 Hide it.
1559
1560 >>> chart.toggle()
1561 >>> chart.show()
1562
1563 """
1564 self.visible = not self.visible
1565
1566 @property
1567 @doc_subs
1568 def title(self): # numpydoc ignore=RT01
1569 """Return or set the chart's title.
1570
1571 Examples
1572 --------
1573 Create a {chart_name} with title 'My Chart'.
1574
1575 .. pyvista-plot::
1576 :force_static:
1577
1578 >>> import pyvista as pv
1579 >>> chart = pv.{cls}({chart_args}){chart_init}
1580 >>> chart.title = 'My Chart'
1581 >>> chart.show()
1582
1583 """
1584 return self.GetTitle() # type: ignore[attr-defined]
1585
1586 @title.setter
1587 def title(self, val) -> None:
1588 self.SetTitle(val) # type: ignore[attr-defined]
1589
1590 @property
1591 @doc_subs
1592 def legend(self): # numpydoc ignore=RT01
1593 """Return the chart's legend.
1594
1595 Examples
1596 --------
1597 Create a {chart_name} with custom labels and access its legend.
1598
1599 .. pyvista-plot::
1600 :force_static:
1601
1602 >>> import pyvista as pv
1603 >>> chart = pv.{cls}({chart_args}){chart_init}
1604 >>> {chart_set_labels}
1605 >>> legend = chart.legend
1606 >>> chart.show()
1607
1608 """
1609 return self.GetLegend() # type: ignore[attr-defined]
1610
1611 @property
1612 @doc_subs
1613 def legend_visible(self): # numpydoc ignore=RT01
1614 """Return or set the visibility of the chart's legend.
1615
1616 Examples
1617 --------
1618 Create a {chart_name} with custom labels.
1619
1620 .. pyvista-plot::
1621 :force_static:
1622
1623 >>> import pyvista as pv
1624 >>> chart = pv.{cls}({chart_args}){chart_init}
1625 >>> {chart_set_labels}
1626 >>> chart.show()
1627
1628 Hide the legend.
1629
1630 >>> chart.legend_visible = False
1631 >>> chart.show()
1632
1633 """
1634 return self.GetShowLegend() # type: ignore[attr-defined]
1635
1636 @legend_visible.setter
1637 def legend_visible(self, val) -> None:
1638 self.SetShowLegend(val) # type: ignore[attr-defined]
1639
1640 @_deprecate_positional_args
1641 @doc_subs
1642 def show( # noqa: PLR0917
1643 self,
1644 interactive: bool = True, # noqa: FBT001, FBT002
1645 off_screen=None,
1646 full_screen=None,
1647 screenshot=None,
1648 window_size=None,
1649 notebook=None,
1650 background='w',
1651 dev_kwargs=None,
1652 ):
1653 """Show this chart in a self contained plotter.
1654
1655 Parameters
1656 ----------
1657 interactive : bool, default: True
1658 Enable interaction with the chart. Interaction is not enabled
1659 when plotting off screen.
1660
1661 off_screen : bool, optional
1662 Plots off screen when ``True``. Helpful for saving screenshots
1663 without a window popping up. Defaults to active theme setting.
1664
1665 full_screen : bool, optional
1666 Opens window in full screen. When enabled, ignores
1667 ``window_size``. Defaults to active theme setting.
1668
1669 screenshot : str | bool, default: False
1670 Saves screenshot to file when enabled. See:
1671 :func:`Plotter.screenshot() <pyvista.Plotter.screenshot>`.
1672
1673 When ``True``, takes screenshot and returns ``numpy`` array of
1674 image.
1675
1676 window_size : list, optional
1677 Window size in pixels. Defaults to active theme setting.
1678
1679 notebook : bool, optional
1680 When ``True``, the resulting plot is placed inline a
1681 jupyter notebook. Assumes a jupyter console is active.
1682
1683 background : ColorLike, default: "w"
1684 Use to make the entire mesh have a single solid color.
1685 Either a string, RGB list, or hex color string. For example:
1686 ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
1687 ``color='#FFFFFF'``.
1688
1689 dev_kwargs : dict, optional
1690 Optional developer keyword arguments.
1691
1692 Returns
1693 -------
1694 np.ndarray
1695 Numpy array of the last image when ``screenshot=True``
1696 is set. Optionally contains alpha values. Sized:
1697
1698 * [Window height x Window width x 3] if the theme sets
1699 ``transparent_background=False``.
1700 * [Window height x Window width x 4] if the theme sets
1701 ``transparent_background=True``.
1702
1703 Examples
1704 --------
1705 Create a simple {chart_name} and show it.
1706
1707 .. pyvista-plot::
1708 :force_static:
1709
1710 >>> import pyvista as pv
1711 >>> chart = pv.{cls}({chart_args}){chart_init}
1712 >>> chart.show()
1713
1714 """
1715 if dev_kwargs is None:
1716 dev_kwargs = {}
1717 if off_screen is None:
1718 off_screen = pv.OFF_SCREEN
1719 pl = pv.Plotter(window_size=window_size, notebook=notebook, off_screen=off_screen)
1720 pl.background_color = background
1721 pl.add_chart(self)
1722 if interactive and (not off_screen or pv.BUILDING_GALLERY): # pragma: no cover
1723 pl.set_chart_interaction(self)
1724 return pl.show(
1725 screenshot=screenshot,
1726 full_screen=full_screen,
1727 **dev_kwargs,
1728 )
1729
1730
1731 # Subclasses of `_Plot` also inherit from vtk classes, so we disable the vtk snake_case API here
1732 @abstract_class
1733 class _Plot(DocSubs):
1734 """Common pythonic interface for :vtk:`vtkPlot` and :vtk:`vtkPlot3D` instances."""
1735
1736 # Subclasses should specify following substitutions: 'plot_name', 'chart_init' and 'plot_init'.
1737 _DOC_SUBS: dict[str, str] | None = None
1738
1739 def __init__(self, chart) -> None:
1740 super().__init__()
1741 self._chart = weakref.proxy(chart)
1742 self._pen = Pen()
1743 self._brush = Brush()
1744 self._label = ''
1745 if hasattr(self, 'SetPen'):
1746 self.SetPen(self._pen)
1747 if hasattr(self, 'SetBrush'):
1748 self.SetBrush(self._brush)
1749
1750 @property
1751 @doc_subs
1752 def color(self): # numpydoc ignore=RT01
1753 """Return or set the plot's color.
1754
1755 This is the color used by the plot's pen and brush to draw lines and shapes.
1756
1757 Examples
1758 --------
1759 Set the {plot_name}'s color to red.
1760
1761 .. pyvista-plot::
1762 :force_static:
1763
1764 >>> import pyvista as pv
1765 >>> chart = {chart_init}
1766 >>> plot = {plot_init}
1767 >>> plot.color = 'r'
1768 >>> chart.show()
1769
1770 """
1771 return self.pen.color
1772
1773 @color.setter
1774 def color(self, val) -> None:
1775 self.pen.color = val
1776 self.brush.color = val
1777
1778 @property
1779 @doc_subs
1780 def pen(self): # numpydoc ignore=RT01
1781 """Pen object controlling how lines in this plot are drawn.
1782
1783 Returns
1784 -------
1785 Pen
1786 Pen object controlling how lines in this plot are drawn.
1787
1788 Examples
1789 --------
1790 Increase the line width of the {plot_name}'s pen object.
1791
1792 .. pyvista-plot::
1793 :force_static:
1794
1795 >>> import pyvista as pv
1796 >>> chart = {chart_init}
1797 >>> plot = {plot_init}
1798 >>> plot.line_style = '-' # Make sure all lines are visible
1799 >>> plot.pen.width = 10
1800 >>> chart.show()
1801
1802 """
1803 return self._pen
1804
1805 @property
1806 @doc_subs
1807 def brush(self): # numpydoc ignore=RT01
1808 """Brush object controlling how shapes in this plot are filled.
1809
1810 Returns
1811 -------
1812 Brush
1813 Brush object controlling how shapes in this plot are filled.
1814
1815 Examples
1816 --------
1817 Use a custom texture for the {plot_name}'s brush object.
1818
1819 .. pyvista-plot::
1820 :force_static:
1821
1822 >>> import pyvista as pv
1823 >>> from pyvista import examples
1824 >>> chart = {chart_init}
1825 >>> plot = {plot_init}
1826 >>> plot.brush.texture = examples.download_puppy_texture()
1827 >>> chart.show()
1828
1829 """
1830 return self._brush
1831
1832 @property
1833 @doc_subs
1834 def line_width(self): # numpydoc ignore=RT01
1835 """Return or set the line width of all lines drawn in this plot.
1836
1837 This is equivalent to accessing/modifying the width of this plot's pen.
1838
1839 Examples
1840 --------
1841 Set the line width to 10
1842
1843 .. pyvista-plot::
1844 :force_static:
1845
1846 >>> import pyvista as pv
1847 >>> chart = {chart_init}
1848 >>> plot = {plot_init}
1849 >>> plot.line_style = '-' # Make sure all lines are visible
1850 >>> plot.line_width = 10
1851 >>> chart.show()
1852
1853 """
1854 return self.pen.width
1855
1856 @line_width.setter
1857 def line_width(self, val) -> None:
1858 self.pen.width = val
1859
1860 @property
1861 @doc_subs
1862 def line_style(self): # numpydoc ignore=RT01
1863 """Return or set the line style of all lines drawn in this plot.
1864
1865 This is equivalent to accessing/modifying the style of this plot's pen.
1866
1867 Examples
1868 --------
1869 Set a custom line style.
1870
1871 .. pyvista-plot::
1872 :force_static:
1873
1874 >>> import pyvista as pv
1875 >>> chart = {chart_init}
1876 >>> plot = {plot_init}
1877 >>> plot.line_style = '-.'
1878 >>> chart.show()
1879
1880 """
1881 return self.pen.style
1882
1883 @line_style.setter
1884 def line_style(self, val) -> None:
1885 self.pen.style = val
1886
1887 @property
1888 @doc_subs
1889 def label(self): # numpydoc ignore=RT01
1890 """Return or set the this plot's label, as shown in the chart's legend.
1891
1892 Examples
1893 --------
1894 Create a {plot_name} with custom label.
1895
1896 .. pyvista-plot::
1897 :force_static:
1898
1899 >>> import pyvista as pv
1900 >>> chart = {chart_init}
1901 >>> plot = {plot_init}
1902 >>> plot.label = 'My awesome plot'
1903 >>> chart.show()
1904
1905 """
1906 return self._label
1907
1908 @label.setter
1909 def label(self, val) -> None:
1910 self._label = '' if val is None else val
1911 self.SetLabel(self._label) # type: ignore[attr-defined]
1912
1913 @property
1914 @doc_subs
1915 def visible(self): # numpydoc ignore=RT01
1916 """Return or set the this plot's visibility.
1917
1918 Examples
1919 --------
1920 Create a {plot_name}.
1921
1922 .. pyvista-plot::
1923 :force_static:
1924
1925 >>> import pyvista as pv
1926 >>> chart = {chart_init}
1927 >>> plot = {plot_init}
1928 >>> chart.show()
1929
1930 Hide it.
1931
1932 >>> plot.visible = False
1933 >>> chart.show()
1934
1935 """
1936 return self.GetVisible() # type: ignore[attr-defined]
1937
1938 @visible.setter
1939 def visible(self, val) -> None:
1940 self.SetVisible(val) # type: ignore[attr-defined]
1941
1942 @doc_subs
1943 def toggle(self) -> None:
1944 """Toggle the plot's visibility.
1945
1946 Examples
1947 --------
1948 Create a {plot_name}.
1949
1950 .. pyvista-plot::
1951 :force_static:
1952
1953 >>> import pyvista as pv
1954 >>> chart = {chart_init}
1955 >>> plot = {plot_init}
1956 >>> chart.show()
1957
1958 Hide it.
1959
1960 >>> plot.toggle()
1961 >>> chart.show()
1962
1963 """
1964 self.visible = not self.visible
1965
1966
1967 class _MultiCompPlot(_Plot):
1968 """Common pythonic interface for :vtk:`vtkPlot` instances with multiple components.
1969
1970 Example subclasses are BoxPlot, PiePlot, BarPlot and StackPlot.
1971 """
1972
1973 DEFAULT_COLOR_SCHEME = 'qual_accent'
1974
1975 # Subclasses should specify following substitutions: 'plot_name', 'chart_init', 'plot_init',
1976 # 'multichart_init' and 'multiplot_init'.
1977 _DOC_SUBS: dict[str, str] | None = None
1978
1979 def __init__(self, chart) -> None:
1980 super().__init__(chart)
1981 self._color_series = _vtk.vtkColorSeries()
1982 self._lookup_table = self._color_series.CreateLookupTable(_vtk.vtkColorSeries.CATEGORICAL)
1983 self._labels = _vtk.vtkStringArray()
1984 self.SetLabels(self._labels) # type: ignore[attr-defined]
1985 self.color_scheme = self.DEFAULT_COLOR_SCHEME
1986
1987 @property
1988 @doc_subs
1989 def color_scheme(self): # numpydoc ignore=RT01
1990 """Return or set the plot's color scheme.
1991
1992 This scheme defines the colors of the different
1993 components drawn by this plot.
1994 See the table below for the available color
1995 schemes.
1996
1997 Notes
1998 -----
1999 .. _plot_color_schemes:
2000
2001 Overview of all available color schemes.
2002
2003 .. include:: ../plot_color_schemes.rst
2004
2005 Examples
2006 --------
2007 Set the {plot_name}'s color scheme to warm.
2008
2009 .. pyvista-plot::
2010 :force_static:
2011
2012 >>> import pyvista as pv
2013 >>> chart = {multichart_init}
2014 >>> plot = {multiplot_init}
2015 >>> plot.color_scheme = 'warm'
2016 >>> chart.show()
2017
2018 """
2019 return SCHEME_NAMES.get(self._color_series.GetColorScheme(), 'custom')
2020
2021 @color_scheme.setter
2022 def color_scheme(self, val) -> None:
2023 self._color_series.SetColorScheme(COLOR_SCHEMES.get(val, COLOR_SCHEMES['custom'])['id']) # type: ignore[index]
2024 self._color_series.BuildLookupTable(self._lookup_table, _vtk.vtkColorSeries.CATEGORICAL)
2025 self.brush.color = self.colors[0]
2026
2027 @property
2028 @doc_subs
2029 def colors(self): # numpydoc ignore=RT01
2030 """Return or set the plot's colors.
2031
2032 These are the colors used for the different
2033 components drawn by this plot.
2034
2035 Examples
2036 --------
2037 Set the {plot_name}'s colors manually.
2038
2039 .. pyvista-plot::
2040 :force_static:
2041
2042 >>> import pyvista as pv
2043 >>> chart = {multichart_init}
2044 >>> plot = {multiplot_init}
2045 >>> plot.colors = ['b', 'g', 'r', 'c']
2046 >>> chart.show()
2047
2048 """
2049 return [
2050 Color(self._color_series.GetColor(i))
2051 for i in range(self._color_series.GetNumberOfColors())
2052 ]
2053
2054 @colors.setter
2055 def colors(self, val):
2056 if val is None:
2057 self.color_scheme = self.DEFAULT_COLOR_SCHEME
2058 # Setting color_scheme already sets brush.color
2059 elif isinstance(val, str):
2060 self.color_scheme = val
2061 # Setting color_scheme already sets brush.color
2062 else:
2063 try:
2064 self._color_series.SetNumberOfColors(len(val))
2065 for i, color in enumerate(val):
2066 self._color_series.SetColor(i, Color(color).vtk_c3ub)
2067 self._color_series.BuildLookupTable(
2068 self._lookup_table,
2069 _vtk.vtkColorSeries.CATEGORICAL,
2070 )
2071 self.brush.color = self.colors[0] # Synchronize "color" and "colors" properties
2072 except ValueError as e:
2073 self.color_scheme = self.DEFAULT_COLOR_SCHEME
2074 msg = 'Invalid colors specified, falling back to default color scheme.'
2075 raise ValueError(msg) from e
2076
2077 @property
2078 @doc_subs
2079 def color(self): # numpydoc ignore=RT01
2080 """Return or set the plot's color.
2081
2082 This is the color used by the plot's brush
2083 to draw the different components.
2084
2085 Examples
2086 --------
2087 Set the {plot_name}'s color to red.
2088
2089 .. pyvista-plot::
2090 :force_static:
2091
2092 >>> import pyvista as pv
2093 >>> chart = {chart_init}
2094 >>> plot = {plot_init}
2095 >>> plot.color = 'r'
2096 >>> chart.show()
2097
2098 """
2099 return self.brush.color
2100
2101 @color.setter
2102 def color(self, val) -> None:
2103 # Override default _Plot behaviour. This makes sure the plot's "color_scheme", "colors"
2104 # and "color" properties (and their internal representations through color series,
2105 # lookup tables and brushes) stay synchronized.
2106 self.colors = [val]
2107
2108 @property
2109 @doc_subs
2110 def labels(self): # numpydoc ignore=RT01
2111 """Return or set the this plot's labels, as shown in the chart's legend.
2112
2113 Examples
2114 --------
2115 Create a {plot_name}.
2116
2117 .. pyvista-plot::
2118 :force_static:
2119
2120 >>> import pyvista as pv
2121 >>> chart = {multichart_init}
2122 >>> plot = {multiplot_init}
2123 >>> chart.show()
2124
2125 Modify the labels.
2126
2127 >>> plot.labels = ['A', 'B', 'C', 'D']
2128 >>> chart.show()
2129
2130 """
2131 return [self._labels.GetValue(i) for i in range(self._labels.GetNumberOfValues())]
2132
2133 @labels.setter
2134 def labels(self, val):
2135 self._labels.Reset()
2136 if isinstance(val, str):
2137 val = [val]
2138 try:
2139 if val is not None:
2140 for label in val:
2141 self._labels.InsertNextValue(label)
2142 except TypeError:
2143 msg = 'Invalid labels specified.'
2144 raise ValueError(msg)
2145
2146 @property
2147 @doc_subs
2148 def label(self): # numpydoc ignore=RT01
2149 """Return or set the this plot's label, as shown in the chart's legend.
2150
2151 Examples
2152 --------
2153 Create a {plot_name} with custom label.
2154
2155 .. pyvista-plot::
2156 :force_static:
2157
2158 >>> import pyvista as pv
2159 >>> import numpy as np
2160 >>> chart = {chart_init}
2161 >>> plot = {plot_init}
2162 >>> chart.show()
2163
2164 Modify the label.
2165
2166 >>> plot.label = 'My awesome plot'
2167 >>> chart.show()
2168
2169 """
2170 return self.labels[0] if self._labels.GetNumberOfValues() > 0 else ''
2171
2172 @label.setter
2173 def label(self, val) -> None:
2174 # Override default _Plot behaviour. This makes sure the plot's "labels" and "label"
2175 # properties (and their internal representations) stay synchronized.
2176 self.labels = None if val is None else [val]
2177
2178
2179 class LinePlot2D(_NoNewAttrMixin, DisableVtkSnakeCase, _Plot, _vtk.vtkPlotLine):
2180 """Class representing a 2D line plot.
2181
2182 Users should typically not directly create new plot instances, but use the dedicated 2D
2183 chart's plotting methods.
2184
2185 Parameters
2186 ----------
2187 chart : Chart2D
2188 The chart containing this plot.
2189
2190 x : array_like
2191 X coordinates of the points through which a line should be drawn.
2192
2193 y : array_like
2194 Y coordinates of the points through which a line should be drawn.
2195
2196 color : ColorLike, default: "b"
2197 Color of the line drawn in this plot. Any color parsable by :class:`pyvista.Color`
2198 is allowed.
2199
2200 width : float, default: 1
2201 Width of the line drawn in this plot.
2202
2203 style : str, default: "-"
2204 Style of the line drawn in this plot. See :ref:`Pen.LINE_STYLES <pen_line_styles>`
2205 for a list of allowed line styles.
2206
2207 label : str, default: ""
2208 Label of this plot, as shown in the chart's legend.
2209
2210 Examples
2211 --------
2212 Create a 2D chart plotting an approximate satellite
2213 trajectory.
2214
2215
2216 .. pyvista-plot::
2217 :force_static:
2218
2219 >>> import pyvista as pv
2220 >>> from pyvista import examples
2221 >>> import numpy as np
2222 >>> chart = pv.Chart2D()
2223 >>> x = np.linspace(0, 1, 100)
2224 >>> y = np.sin(6.5 * x - 1)
2225 >>> _ = chart.line(x, y, color='y', width=4)
2226 >>> chart.background_texture = examples.load_globe_texture()
2227 >>> chart.hide_axes()
2228 >>> chart.show()
2229
2230 """
2231
2232 _DOC_SUBS = { # noqa: RUF012
2233 'plot_name': '2D line plot',
2234 'chart_init': 'pv.Chart2D()',
2235 'plot_init': 'chart.line([0, 1, 2], [2, 1, 3])',
2236 }
2237
2238 @_deprecate_positional_args(allowed=['chart', 'x', 'y'])
2239 def __init__( # noqa: PLR0917
2240 self,
2241 chart,
2242 x,
2243 y,
2244 color='b',
2245 width=1.0,
2246 style='-',
2247 label='',
2248 ) -> None: # numpydoc ignore=PR01,RT01
2249 """Initialize a new 2D line plot instance."""
2250 super().__init__(chart)
2251 self._table = pv.Table({'x': np.empty(0, np.float32), 'y': np.empty(0, np.float32)})
2252 self.SetInputData(self._table, 'x', 'y')
2253 self.update(x, y)
2254 self.color = color
2255 self.line_width = width
2256 self.line_style = style
2257 self.label = label
2258
2259 @property
2260 def x(self): # numpydoc ignore=RT01
2261 """Retrieve the X coordinates of the points through which a line is drawn.
2262
2263 Examples
2264 --------
2265 Create a line plot and display the x coordinates.
2266
2267 .. pyvista-plot::
2268 :force_static:
2269
2270 >>> import pyvista as pv
2271 >>> chart = pv.Chart2D()
2272 >>> plot = chart.line([0, 1, 2], [2, 1, 3])
2273 >>> plot.x
2274 pyvista_ndarray([0, 1, 2])
2275 >>> chart.show()
2276
2277 """
2278 return self._table['x']
2279
2280 @property
2281 def y(self): # numpydoc ignore=RT01
2282 """Retrieve the Y coordinates of the points through which a line is drawn.
2283
2284 Examples
2285 --------
2286 Create a line plot and display the y coordinates.
2287
2288 .. pyvista-plot::
2289 :force_static:
2290
2291 >>> import pyvista as pv
2292 >>> chart = pv.Chart2D()
2293 >>> plot = chart.line([0, 1, 2], [2, 1, 3])
2294 >>> plot.y
2295 pyvista_ndarray([2, 1, 3])
2296 >>> chart.show()
2297
2298 """
2299 return self._table['y']
2300
2301 def update(self, x, y) -> None:
2302 """Update this plot's points, through which a line is drawn.
2303
2304 Parameters
2305 ----------
2306 x : array_like
2307 The new x coordinates of the points through which a line should be drawn.
2308
2309 y : array_like
2310 The new y coordinates of the points through which a line should be drawn.
2311
2312 Examples
2313 --------
2314 Create a line plot.
2315
2316 .. pyvista-plot::
2317 :force_static:
2318
2319 >>> import pyvista as pv
2320 >>> chart = pv.Chart2D()
2321 >>> plot = chart.line([0, 1, 2], [2, 1, 3])
2322 >>> chart.show()
2323
2324 Update the line's y coordinates.
2325
2326 >>> plot.update([0, 1, 2], [3, 1, 2])
2327 >>> chart.show()
2328
2329 """
2330 if len(x) > 1:
2331 self._table.update({'x': np.asarray(x), 'y': np.asarray(y)})
2332 self.visible = True
2333 else:
2334 # Turn off visibility for fewer than 2 points as otherwise an error message is shown
2335 self.visible = False
2336
2337
2338 class ScatterPlot2D(_NoNewAttrMixin, DisableVtkSnakeCase, _Plot, _vtk.vtkPlotPoints):
2339 """Class representing a 2D scatter plot.
2340
2341 Users should typically not directly create new plot instances, but use the dedicated 2D
2342 chart's plotting methods.
2343
2344 Parameters
2345 ----------
2346 chart : Chart2D
2347 The chart containing this plot.
2348
2349 x : array_like
2350 X coordinates of the points to draw.
2351
2352 y : array_like
2353 Y coordinates of the points to draw.
2354
2355 color : ColorLike, default: "b"
2356 Color of the points drawn in this plot. Any color parsable by :class:`pyvista.Color`
2357 is allowed.
2358
2359 size : float, default: 10
2360 Size of the point markers drawn in this plot.
2361
2362 style : str, default: "o"
2363 Style of the point markers drawn in this plot. See
2364 :ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
2365 for a list of allowed marker styles.
2366
2367 label : str, default: ""
2368 Label of this plot, as shown in the chart's legend.
2369
2370 Notes
2371 -----
2372 .. _scatter_marker_styles:
2373
2374 MARKER_STYLES : dict
2375 Dictionary containing all allowed marker styles as its keys.
2376
2377 .. include:: ../scatter_marker_styles.rst
2378
2379 Examples
2380 --------
2381 Plot a simple sine wave as a scatter plot.
2382
2383 .. pyvista-plot::
2384 :force_static:
2385
2386 >>> import pyvista as pv
2387 >>> import numpy as np
2388 >>> x = np.linspace(0, 2 * np.pi, 20)
2389 >>> y = np.sin(x)
2390 >>> chart = pv.Chart2D()
2391 >>> _ = chart.scatter(x, y)
2392 >>> chart.show()
2393
2394 """
2395
2396 MARKER_STYLES: ClassVar[
2397 dict[str, dict[str, int | str]]
2398 ] = { # descr is used in the documentation, set to None to hide it from the docs.
2399 '': {'id': _vtk.vtkPlotPoints.NONE, 'descr': 'Hidden'},
2400 'x': {'id': _vtk.vtkPlotPoints.CROSS, 'descr': 'Cross'},
2401 '+': {'id': _vtk.vtkPlotPoints.PLUS, 'descr': 'Plus'},
2402 's': {'id': _vtk.vtkPlotPoints.SQUARE, 'descr': 'Square'},
2403 'o': {'id': _vtk.vtkPlotPoints.CIRCLE, 'descr': 'Circle'},
2404 'd': {'id': _vtk.vtkPlotPoints.DIAMOND, 'descr': 'Diamond'},
2405 }
2406 _DOC_SUBS = { # noqa: RUF012
2407 'plot_name': '2D scatter plot',
2408 'chart_init': 'pv.Chart2D()',
2409 'plot_init': 'chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])',
2410 }
2411
2412 @_deprecate_positional_args(allowed=['chart', 'x', 'y'])
2413 def __init__( # noqa: PLR0917
2414 self,
2415 chart,
2416 x,
2417 y,
2418 color='b',
2419 size=10,
2420 style='o',
2421 label='',
2422 ) -> None: # numpydoc ignore=PR01,RT01
2423 """Initialize a new 2D scatter plot instance."""
2424 super().__init__(chart)
2425 self._table = pv.Table({'x': np.empty(0, np.float32), 'y': np.empty(0, np.float32)})
2426 self.SetInputData(self._table, 'x', 'y')
2427 self.update(x, y)
2428 self.color = color
2429 self.marker_size = size
2430 self.marker_style = style
2431 self.label = label
2432
2433 @property
2434 def x(self): # numpydoc ignore=RT01
2435 """Retrieve the X coordinates of this plot's points.
2436
2437 Examples
2438 --------
2439 Create a scatter plot and display the x coordinates.
2440
2441 .. pyvista-plot::
2442 :force_static:
2443
2444 >>> import pyvista as pv
2445 >>> chart = pv.Chart2D()
2446 >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
2447 >>> plot.x
2448 pyvista_ndarray([0, 1, 2, 3, 4])
2449 >>> chart.show()
2450
2451 """
2452 return self._table['x']
2453
2454 @property
2455 def y(self): # numpydoc ignore=RT01
2456 """Retrieve the Y coordinates of this plot's points.
2457
2458 Examples
2459 --------
2460 Create a scatter plot and display the y coordinates.
2461
2462 .. pyvista-plot::
2463 :force_static:
2464
2465 >>> import pyvista as pv
2466 >>> chart = pv.Chart2D()
2467 >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
2468 >>> plot.y
2469 pyvista_ndarray([2, 1, 3, 4, 2])
2470 >>> chart.show()
2471
2472 """
2473 return self._table['y']
2474
2475 def update(self, x, y) -> None:
2476 """Update this plot's points.
2477
2478 Parameters
2479 ----------
2480 x : array_like
2481 The new x coordinates of the points to draw.
2482
2483 y : array_like
2484 The new y coordinates of the points to draw.
2485
2486 Examples
2487 --------
2488 Create a scatter plot.
2489
2490 .. pyvista-plot::
2491 :force_static:
2492
2493 >>> import pyvista as pv
2494 >>> chart = pv.Chart2D()
2495 >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
2496 >>> chart.show()
2497
2498 Update the marker locations.
2499
2500 >>> plot.update([0, 1, 2, 3, 4], [3, 2, 4, 2, 1])
2501 >>> chart.show()
2502
2503 """
2504 if len(x) > 0:
2505 self._table.update({'x': np.asarray(x), 'y': np.asarray(y)})
2506 self.visible = True
2507 else:
2508 self.visible = False
2509
2510 @property
2511 def marker_size(self): # numpydoc ignore=RT01
2512 """Return or set the plot's marker size.
2513
2514 Examples
2515 --------
2516 Create a 2D scatter plot.
2517
2518 .. pyvista-plot::
2519 :force_static:
2520
2521 >>> import pyvista as pv
2522 >>> chart = pv.Chart2D()
2523 >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
2524 >>> chart.show()
2525
2526 Increase the marker size.
2527
2528 >>> plot.marker_size = 30
2529 >>> chart.show()
2530
2531 """
2532 return self.GetMarkerSize()
2533
2534 @marker_size.setter
2535 def marker_size(self, val) -> None:
2536 self.SetMarkerSize(val)
2537
2538 @property
2539 def marker_style(self): # numpydoc ignore=RT01
2540 """Return or set the plot's marker style.
2541
2542 Examples
2543 --------
2544 Create a 2D scatter plot.
2545
2546 .. pyvista-plot::
2547 :force_static:
2548
2549 >>> import pyvista as pv
2550 >>> chart = pv.Chart2D()
2551 >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
2552 >>> chart.show()
2553
2554 Change the marker style.
2555
2556 >>> plot.marker_style = 'd'
2557 >>> chart.show()
2558
2559 """
2560 return self._marker_style
2561
2562 @marker_style.setter
2563 def marker_style(self, val):
2564 if val is None:
2565 val = ''
2566 try:
2567 self.SetMarkerStyle(self.MARKER_STYLES[val]['id']) # type: ignore[arg-type]
2568 self._marker_style = val
2569 except KeyError:
2570 formatted_styles = '", "'.join(self.MARKER_STYLES.keys())
2571 msg = f'Invalid marker style. Allowed marker styles: "{formatted_styles}"'
2572 raise ValueError(msg)
2573
2574
2575 class AreaPlot(_NoNewAttrMixin, DisableVtkSnakeCase, _Plot, _vtk.vtkPlotArea):
2576 """Class representing a 2D area plot.
2577
2578 Users should typically not directly create new plot instances, but use the dedicated 2D
2579 chart's plotting methods.
2580
2581 Parameters
2582 ----------
2583 chart : Chart2D
2584 The chart containing this plot.
2585
2586 x : array_like
2587 X coordinates of the points outlining the area to draw.
2588
2589 y1 : array_like
2590 Y coordinates of the points on the first outline of the area to draw.
2591
2592 y2 : array_like, optional
2593 Y coordinates of the points on the second outline of the area to
2594 draw. Defaults to ``numpy.zeros_like(x)``.
2595
2596 color : ColorLike, default: "b"
2597 Color of the area drawn in this plot. Any color parsable by :class:`pyvista.Color` is
2598 allowed.
2599
2600 label : str, default: ""
2601 Label of this plot, as shown in the chart's legend.
2602
2603 Examples
2604 --------
2605 Create an area plot showing the minimum and maximum precipitation observed in each month.
2606
2607 .. pyvista-plot::
2608 :force_static:
2609
2610 >>> import pyvista as pv
2611 >>> import numpy as np
2612 >>> x = np.arange(12)
2613 >>> p_min = [11, 0, 16, 2, 23, 18, 25, 17, 9, 12, 14, 21]
2614 >>> p_max = [87, 64, 92, 73, 91, 94, 107, 101, 84, 88, 95, 103]
2615 >>> chart = pv.Chart2D()
2616 >>> _ = chart.area(x, p_min, p_max)
2617 >>> chart.x_axis.tick_locations = x
2618 >>> chart.x_axis.tick_labels = [
2619 ... 'Jan',
2620 ... 'Feb',
2621 ... 'Mar',
2622 ... 'Apr',
2623 ... 'May',
2624 ... 'Jun',
2625 ... 'Jul',
2626 ... 'Aug',
2627 ... 'Sep',
2628 ... 'Oct',
2629 ... 'Nov',
2630 ... 'Dec',
2631 ... ]
2632 >>> chart.x_axis.label = 'Month'
2633 >>> chart.y_axis.label = 'Precipitation [mm]'
2634 >>> chart.show()
2635
2636 """
2637
2638 _DOC_SUBS = { # noqa: RUF012
2639 'plot_name': 'area plot',
2640 'chart_init': 'pv.Chart2D()',
2641 'plot_init': 'chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])',
2642 }
2643
2644 @_deprecate_positional_args(allowed=['chart', 'x', 'y1', 'y2'], n_allowed=4)
2645 def __init__(self, chart, x, y1, y2=None, color='b', label='') -> None: # noqa: PLR0917
2646 """Initialize a new 2D area plot instance."""
2647 super().__init__(chart)
2648 self._table = pv.Table(
2649 {
2650 'x': np.empty(0, np.float32),
2651 'y1': np.empty(0, np.float32),
2652 'y2': np.empty(0, np.float32),
2653 },
2654 )
2655 self.SetInputData(self._table)
2656 self.SetInputArray(0, 'x')
2657 self.SetInputArray(1, 'y1')
2658 self.SetInputArray(2, 'y2')
2659 self.update(x, y1, y2)
2660 self.color = color
2661 self.label = label
2662
2663 @property
2664 def x(self): # numpydoc ignore=RT01
2665 """Retrieve the X coordinates of the points outlining the drawn area.
2666
2667 Examples
2668 --------
2669 Create an area plot and display the x coordinates.
2670
2671 .. pyvista-plot::
2672 :force_static:
2673
2674 >>> import pyvista as pv
2675 >>> chart = pv.Chart2D()
2676 >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
2677 >>> plot.x
2678 pyvista_ndarray([0, 1, 2])
2679 >>> chart.show()
2680
2681 """
2682 return self._table['x']
2683
2684 @property
2685 def y1(self): # numpydoc ignore=RT01
2686 """Retrieve the Y coordinates of the points on the first outline of the drawn area.
2687
2688 Examples
2689 --------
2690 Create an area plot and display the y1 coordinates.
2691
2692 .. pyvista-plot::
2693 :force_static:
2694
2695 >>> import pyvista as pv
2696 >>> chart = pv.Chart2D()
2697 >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
2698 >>> plot.y1
2699 pyvista_ndarray([2, 1, 3])
2700 >>> chart.show()
2701
2702 """
2703 return self._table['y1']
2704
2705 @property
2706 def y2(self): # numpydoc ignore=RT01
2707 """Retrieve the Y coordinates of the points on the second outline of the drawn area.
2708
2709 Examples
2710 --------
2711 Create an area plot and display the y2 coordinates.
2712
2713 .. pyvista-plot::
2714 :force_static:
2715
2716 >>> import pyvista as pv
2717 >>> chart = pv.Chart2D()
2718 >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
2719 >>> plot.y2
2720 pyvista_ndarray([1, 0, 1])
2721 >>> chart.show()
2722
2723 """
2724 return self._table['y2']
2725
2726 def update(self, x, y1, y2=None) -> None:
2727 """Update this plot's points, outlining the area to draw.
2728
2729 Parameters
2730 ----------
2731 x : array_like
2732 The new x coordinates of the points outlining the area.
2733
2734 y1 : array_like
2735 The new y coordinates of the points on the first outline of the area.
2736
2737 y2 : array_like, optional
2738 The new y coordinates of the points on the second outline of the
2739 area. Default ``numpy.zeros_like(x)``.
2740
2741 Examples
2742 --------
2743 Create an area plot.
2744
2745 .. pyvista-plot::
2746 :force_static:
2747
2748 >>> import pyvista as pv
2749 >>> chart = pv.Chart2D()
2750 >>> plot = chart.area([0, 1, 2], [2, 1, 3])
2751 >>> chart.show()
2752
2753 Update the points on the second outline of the area.
2754
2755 >>> plot.update([0, 1, 2], [2, 1, 3], [1, 0, 1])
2756 >>> chart.show()
2757
2758 """
2759 if len(x) > 0:
2760 if y2 is None:
2761 y2 = np.zeros_like(x)
2762 self._table.update(
2763 {
2764 'x': np.asarray(x),
2765 'y1': np.asarray(y1),
2766 'y2': np.asarray(y2),
2767 },
2768 )
2769 self.visible = True
2770 else:
2771 self.visible = False
2772
2773
2774 class BarPlot(_NoNewAttrMixin, DisableVtkSnakeCase, _MultiCompPlot, _vtk.vtkPlotBar):
2775 """Class representing a 2D bar plot.
2776
2777 Users should typically not directly create new plot instances, but use the dedicated 2D
2778 chart's plotting methods.
2779
2780 Parameters
2781 ----------
2782 chart : Chart2D
2783 The chart containing this plot.
2784
2785 x : array_like
2786 Positions (along the x-axis for a vertical orientation, along the y-axis for
2787 a horizontal orientation) of the bars to draw.
2788
2789 y : array_like
2790 Size of the bars to draw. Multiple bars can be stacked by passing a sequence of sequences.
2791
2792 color : ColorLike, default: "b"
2793 Color of the bars drawn in this plot. Any color parsable by :class:`pyvista.Color` is
2794 allowed.
2795
2796 orientation : str, default: "V"
2797 Orientation of the bars drawn in this plot. Either ``"H"`` for an horizontal orientation
2798 or ``"V"`` for a vertical orientation.
2799
2800 label : str, default: ""
2801 Label of this plot, as shown in the chart's legend.
2802
2803 Examples
2804 --------
2805 Create a stacked bar chart showing the average time spent on activities
2806 throughout the week.
2807
2808 .. pyvista-plot::
2809 :force_static:
2810
2811 >>> import pyvista as pv
2812 >>> import numpy as np
2813 >>> x = np.arange(1, 8)
2814 >>> y_s = [7, 8, 7.5, 8, 7.5, 9, 10]
2815 >>> y_h = [2, 3, 2, 2.5, 1.5, 4, 6.5]
2816 >>> y_w = [8, 8, 7, 8, 7, 0, 0]
2817 >>> y_r = [5, 2.5, 4.5, 3.5, 6, 9, 6.5]
2818 >>> y_t = [2, 2.5, 3, 2, 2, 2, 1]
2819 >>> labels = ['Sleep', 'Household', 'Work', 'Relax', 'Transport']
2820 >>> chart = pv.Chart2D()
2821 >>> _ = chart.bar(x, [y_s, y_h, y_w, y_r, y_t], label=labels)
2822 >>> chart.x_axis.tick_locations = x
2823 >>> chart.x_axis.tick_labels = [
2824 ... 'Mon',
2825 ... 'Tue',
2826 ... 'Wed',
2827 ... 'Thu',
2828 ... 'Fri',
2829 ... 'Sat',
2830 ... 'Sun',
2831 ... ]
2832 >>> chart.x_label = 'Day of week'
2833 >>> chart.y_label = 'Average time spent'
2834 >>> chart.grid = False # Disable the grid lines
2835 >>> chart.show()
2836
2837 """
2838
2839 ORIENTATIONS: ClassVar[dict[str, int]] = {
2840 'H': _vtk.vtkPlotBar.HORIZONTAL,
2841 'V': _vtk.vtkPlotBar.VERTICAL,
2842 }
2843 _DOC_SUBS = { # noqa: RUF012
2844 'plot_name': 'bar plot',
2845 'chart_init': 'pv.Chart2D()',
2846 'plot_init': 'chart.bar([1, 2, 3], [2, 1, 3])',
2847 'multichart_init': 'pv.Chart2D()',
2848 'multiplot_init': 'chart.bar([1, 2, 3], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])',
2849 }
2850
2851 @_deprecate_positional_args(allowed=['chart', 'x', 'y'])
2852 def __init__( # noqa: PLR0917
2853 self,
2854 chart,
2855 x,
2856 y,
2857 color=None,
2858 orientation='V',
2859 label=None,
2860 ) -> None: # numpydoc ignore=PR01,RT01
2861 """Initialize a new 2D bar plot instance."""
2862 super().__init__(chart)
2863 if not isinstance(y[0], (Sequence, np.ndarray)):
2864 y = (y,)
2865 y_data = {f'y{i}': np.empty(0, np.float32) for i in range(len(y))}
2866 self._table = pv.Table({'x': np.empty(0, np.float32), **y_data})
2867 self.SetInputData(self._table, 'x', 'y0')
2868 for i in range(1, len(y)):
2869 self.SetInputArray(i + 1, f'y{i}')
2870 self.update(x, y)
2871
2872 if len(y) > 1:
2873 self.SetColorSeries(self._color_series)
2874 self.colors = color # None will use default scheme
2875 self.labels = label
2876 else:
2877 # Use blue bars by default in single component mode
2878 self.color = 'b' if color is None else color
2879 self.label = label
2880 self.orientation = orientation
2881
2882 @property
2883 def x(self): # numpydoc ignore=RT01
2884 """Retrieve the positions of the drawn bars.
2885
2886 Examples
2887 --------
2888 Create a bar plot and display the positions.
2889
2890 .. pyvista-plot::
2891 :force_static:
2892
2893 >>> import pyvista as pv
2894 >>> chart = pv.Chart2D()
2895 >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
2896 >>> plot.x
2897 pyvista_ndarray([1, 2, 3])
2898 >>> chart.show()
2899
2900 """
2901 return self._table['x']
2902
2903 @property
2904 def y(self): # numpydoc ignore=RT01
2905 """Retrieve the sizes of the drawn bars.
2906
2907 Examples
2908 --------
2909 Create a bar plot and display the sizes.
2910
2911 .. pyvista-plot::
2912 :force_static:
2913
2914 >>> import pyvista as pv
2915 >>> chart = pv.Chart2D()
2916 >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
2917 >>> plot.y
2918 (pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
2919 >>> chart.show()
2920
2921 """
2922 return tuple(self._table[f'y{i}'] for i in range(self._table.n_arrays - 1))
2923
2924 def update(self, x, y) -> None:
2925 """Update the positions and/or size of the bars in this plot.
2926
2927 Parameters
2928 ----------
2929 x : array_like
2930 The new positions of the bars to draw.
2931
2932 y : array_like
2933 The new sizes of the bars to draw.
2934
2935 Examples
2936 --------
2937 Create a bar plot.
2938
2939 .. pyvista-plot::
2940 :force_static:
2941
2942 >>> import pyvista as pv
2943 >>> chart = pv.Chart2D()
2944 >>> plot = chart.bar([1, 2, 3], [2, 1, 3])
2945 >>> chart.show()
2946
2947 Update the bar sizes.
2948
2949 >>> plot.update([1, 2, 3], [3, 1, 2])
2950 >>> chart.show()
2951
2952 """
2953 if len(x) > 0:
2954 if not isinstance(y[0], (Sequence, np.ndarray)):
2955 y = (y,)
2956 y_data = {f'y{i}': np.asarray(y[i]) for i in range(len(y))}
2957 self._table.update({'x': np.asarray(x), **y_data})
2958 self.visible = True
2959 else:
2960 self.visible = False
2961
2962 @property
2963 def orientation(self): # numpydoc ignore=RT01
2964 """Return or set the orientation of the bars in this plot.
2965
2966 Examples
2967 --------
2968 Create a bar plot.
2969
2970 .. pyvista-plot::
2971 :force_static:
2972
2973 >>> import pyvista as pv
2974 >>> chart = pv.Chart2D()
2975 >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 3, 2]])
2976 >>> chart.show()
2977
2978 Change the orientation to horizontal.
2979
2980 >>> plot.orientation = 'H'
2981 >>> chart.show()
2982
2983 """
2984 return self._orientation
2985
2986 @orientation.setter
2987 def orientation(self, val):
2988 try:
2989 self.SetOrientation(self.ORIENTATIONS[val])
2990 self._orientation = val
2991 except KeyError:
2992 formatted_orientations = '", "'.join(self.ORIENTATIONS.keys())
2993 msg = f'Invalid orientation. Allowed orientations: "{formatted_orientations}"'
2994 raise ValueError(msg)
2995
2996
2997 class StackPlot(_NoNewAttrMixin, DisableVtkSnakeCase, _MultiCompPlot, _vtk.vtkPlotStacked):
2998 """Class representing a 2D stack plot.
2999
3000 Users should typically not directly create new plot instances, but use the dedicated 2D
3001 chart's plotting methods.
3002
3003 Parameters
3004 ----------
3005 chart : Chart2D
3006 The chart containing this plot.
3007
3008 x : array_like
3009 X coordinates of the points outlining the stacks (areas) to draw.
3010
3011 ys : sequence[array_like]
3012 Size of the stacks (areas) to draw at the corresponding X
3013 coordinates. Each sequence defines the sizes of one stack
3014 (area), which are stacked on top of each other.
3015
3016 colors : sequence[ColorLike], optional
3017 Color of the stacks (areas) drawn in this plot. Any color
3018 parsable by :class:`pyvista.Color` is allowed.
3019
3020 labels : sequence[str], default: []
3021 Label for each stack (area) drawn in this plot, as shown in
3022 the chart's legend.
3023
3024 Examples
3025 --------
3026 Create a stack plot showing the amount of vehicles sold per type.
3027
3028 .. pyvista-plot::
3029 :force_static:
3030
3031 >>> import pyvista as pv
3032 >>> import numpy as np
3033 >>> year = [f'{y}' for y in np.arange(2011, 2021)]
3034 >>> x = np.arange(len(year))
3035 >>> n_e = [1739, 4925, 9515, 21727, 31452, 29926, 40648, 57761, 76370, 93702]
3036 >>> n_h = [5563, 7642, 11937, 13905, 22807, 46700, 60875, 53689, 46650, 50321]
3037 >>> n_f = [
3038 ... 166556,
3039 ... 157249,
3040 ... 151552,
3041 ... 138183,
3042 ... 129669,
3043 ... 113985,
3044 ... 92965,
3045 ... 73683,
3046 ... 57097,
3047 ... 29499,
3048 ... ]
3049 >>> chart = pv.Chart2D()
3050 >>> plot = chart.stack(x, [n_e, n_h, n_f])
3051 >>> plot.labels = ['Electric', 'Hybrid', 'Fossil']
3052 >>> chart.x_axis.label = 'Year'
3053 >>> chart.x_axis.tick_locations = x
3054 >>> chart.x_axis.tick_labels = year
3055 >>> chart.y_axis.label = 'New car sales'
3056 >>> chart.show()
3057
3058 """
3059
3060 _DOC_SUBS = { # noqa: RUF012
3061 'plot_name': 'stack plot',
3062 'chart_init': 'pv.Chart2D()',
3063 'plot_init': 'chart.stack([0, 1, 2], [2, 1, 3])',
3064 'multichart_init': 'pv.Chart2D()',
3065 'multiplot_init': 'chart.stack([0, 1, 2], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])',
3066 }
3067
3068 @_deprecate_positional_args(allowed=['chart', 'x', 'ys'])
3069 def __init__( # noqa: PLR0917
3070 self, chart, x, ys, colors=None, labels=None
3071 ) -> None:
3072 """Initialize a new 2D stack plot instance."""
3073 super().__init__(chart)
3074 if not isinstance(ys[0], (Sequence, np.ndarray)):
3075 ys = (ys,)
3076 y_data = {f'y{i}': np.empty(0, np.float32) for i in range(len(ys))}
3077 self._table = pv.Table({'x': np.empty(0, np.float32), **y_data})
3078 self.SetInputData(self._table, 'x', 'y0')
3079 for i in range(1, len(ys)):
3080 self.SetInputArray(i + 1, f'y{i}')
3081 self.update(x, ys)
3082
3083 if len(ys) > 1:
3084 self.SetColorSeries(self._color_series)
3085 self.colors = colors # None will use default scheme
3086 self.labels = labels
3087 else:
3088 self.color = 'b' if colors is None else colors
3089 self.label = labels
3090 self.pen.style = None # Hide lines by default
3091
3092 @property
3093 def x(self): # numpydoc ignore=RT01
3094 """Retrieve the X coordinates of the drawn stacks.
3095
3096 Examples
3097 --------
3098 Create a stack plot and display the x coordinates.
3099
3100 .. pyvista-plot::
3101 :force_static:
3102
3103 >>> import pyvista as pv
3104 >>> chart = pv.Chart2D()
3105 >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
3106 >>> plot.x
3107 pyvista_ndarray([0, 1, 2])
3108 >>> chart.show()
3109
3110 """
3111 return self._table['x']
3112
3113 @property
3114 def ys(self): # numpydoc ignore=RT01
3115 """Retrieve the sizes of the drawn stacks.
3116
3117 Examples
3118 --------
3119 Create a stack plot and display the sizes.
3120
3121 .. pyvista-plot::
3122 :force_static:
3123
3124 >>> import pyvista as pv
3125 >>> chart = pv.Chart2D()
3126 >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
3127 >>> plot.ys
3128 (pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
3129 >>> chart.show()
3130
3131 """
3132 return tuple(self._table[f'y{i}'] for i in range(self._table.n_arrays - 1))
3133
3134 def update(self, x, ys) -> None:
3135 """Update the locations and/or size of the stacks (areas) in this plot.
3136
3137 Parameters
3138 ----------
3139 x : array_like
3140 The new x coordinates of the stacks (areas) to draw.
3141
3142 ys : sequence[array_like]
3143 The new sizes of the stacks (areas) to draw.
3144
3145 Examples
3146 --------
3147 Create a stack plot.
3148
3149 .. pyvista-plot::
3150 :force_static:
3151
3152 >>> import pyvista as pv
3153 >>> chart = pv.Chart2D()
3154 >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 1]])
3155 >>> chart.show()
3156
3157 Update the stack sizes.
3158
3159 >>> plot.update([0, 1, 2], [[3, 1, 2], [0, 3, 1]])
3160 >>> chart.show()
3161
3162 """
3163 if len(x) > 0:
3164 if not isinstance(ys[0], (Sequence, np.ndarray)):
3165 ys = (ys,)
3166 y_data = {f'y{i}': np.asarray(ys[i]) for i in range(len(ys))}
3167 self._table.update({'x': np.asarray(x), **y_data})
3168 self.visible = True
3169 else:
3170 self.visible = False
3171
3172
3173 class Chart2D(_NoNewAttrMixin, DisableVtkSnakeCase, _Chart, _vtk.vtkChartXY):
3174 """2D chart class similar to a ``matplotlib`` figure.
3175
3176 Parameters
3177 ----------
3178 size : sequence[float], default: (1, 1)
3179 Size of the chart in normalized coordinates. A size of ``(0,
3180 0)`` is invisible, a size of ``(1, 1)`` occupies the whole
3181 renderer's width and height.
3182
3183 loc : sequence[float], default: (0, 0)
3184 Location of the chart (its bottom left corner) in normalized
3185 coordinates. A location of ``(0, 0)`` corresponds to the
3186 renderer's bottom left corner, a location of ``(1, 1)``
3187 corresponds to the renderer's top right corner.
3188
3189 x_label : str, default: "x"
3190 Label along the x-axis.
3191
3192 y_label : str, default: "y"
3193 Label along the y-axis.
3194
3195 grid : bool, default: True
3196 Show the background grid in the plot.
3197
3198 See Also
3199 --------
3200 :ref:`chart_basics_example`
3201 :ref:`chart_overlays_example`
3202
3203 Examples
3204 --------
3205 Plot a simple sine wave as a scatter and line plot.
3206
3207 .. pyvista-plot::
3208 :force_static:
3209
3210 >>> import pyvista as pv
3211 >>> import numpy as np
3212 >>> x = np.linspace(0, 2 * np.pi, 20)
3213 >>> y = np.sin(x)
3214 >>> chart = pv.Chart2D()
3215 >>> _ = chart.scatter(x, y)
3216 >>> _ = chart.line(x, y, color='r')
3217 >>> chart.show()
3218
3219 Combine multiple types of plots in the same chart.
3220
3221 >>> rng = np.random.default_rng(1)
3222 >>> x = np.arange(1, 8)
3223 >>> y = rng.integers(5, 15, 7)
3224 >>> e = np.abs(rng.normal(scale=2, size=7))
3225 >>> z = rng.integers(0, 5, 7)
3226 >>> chart = pv.Chart2D()
3227 >>> _ = chart.area(x, y - e, y + e, color=(0.12, 0.46, 0.71, 0.2))
3228 >>> _ = chart.line(x, y, color='tab:blue', style='--', label='Scores')
3229 >>> _ = chart.scatter(x, y, color='tab:blue', style='d')
3230 >>> _ = chart.bar(x, z, color='tab:orange', label='Violations')
3231 >>> chart.x_axis.tick_locations = x
3232 >>> chart.x_axis.tick_labels = [
3233 ... 'Mon',
3234 ... 'Tue',
3235 ... 'Wed',
3236 ... 'Thu',
3237 ... 'Fri',
3238 ... 'Sat',
3239 ... 'Sun',
3240 ... ]
3241 >>> chart.x_label = 'Day of week'
3242 >>> chart.show()
3243
3244 """
3245
3246 PLOT_TYPES: ClassVar[
3247 dict[
3248 str,
3249 (type[ScatterPlot2D | LinePlot2D | AreaPlot | BarPlot | StackPlot]),
3250 ]
3251 ] = {
3252 'scatter': ScatterPlot2D,
3253 'line': LinePlot2D,
3254 'area': AreaPlot,
3255 'bar': BarPlot,
3256 'stack': StackPlot,
3257 }
3258 _PLOT_CLASSES: ClassVar[
3259 dict[
3260 (type[ScatterPlot2D | LinePlot2D | AreaPlot | BarPlot | StackPlot]),
3261 str,
3262 ]
3263 ] = {plot_class: plot_type for (plot_type, plot_class) in PLOT_TYPES.items()}
3264 _DOC_SUBS = { # noqa: RUF012
3265 'chart_name': '2D chart',
3266 'chart_args': '',
3267 'chart_init': """
3268 >>> plot = chart.line([0, 1, 2], [2, 1, 3])""",
3269 'chart_set_labels': 'plot.label = "My awesome plot"',
3270 }
3271
3272 @_deprecate_positional_args
3273 def __init__( # noqa: PLR0917
3274 self,
3275 size=(1, 1),
3276 loc=(0, 0),
3277 x_label='x',
3278 y_label='y',
3279 grid: bool = True, # noqa: FBT001, FBT002
3280 ) -> None: # numpydoc ignore=PR01,RT01
3281 """Initialize the chart."""
3282 super().__init__(size, loc)
3283 self._plots = {plot_type: [] for plot_type in self.PLOT_TYPES.keys()} # type: ignore[var-annotated]
3284 self.SetAutoSize(False) # We manually set the appropriate size
3285 # Overwrite custom x-axis and y-axis using a wrapper object, as using the
3286 # SetAxis method causes a crash at the end of the script's execution (nonzero exit code).
3287 self._x_axis = Axis(_wrap=self.GetAxis(_vtk.vtkAxis.BOTTOM)) # type: ignore[call-arg]
3288 self._y_axis = Axis(_wrap=self.GetAxis(_vtk.vtkAxis.LEFT)) # type: ignore[call-arg]
3289 # Note: registering the axis prevents the nonzero exit code at the end, however
3290 # this results in memory leaks in the plotting tests.
3291 # self.SetAxis(_vtk.vtkAxis.BOTTOM, self._x_axis)
3292 # self.SetAxis(_vtk.vtkAxis.LEFT, self._y_axis)
3293 # self.Register(self._x_axis)
3294 # self.Register(self._y_axis)
3295 self.x_label = x_label
3296 self.y_label = y_label
3297 self.grid = grid
3298 self.legend_visible = True
3299
3300 def _render_event(self, *args, plotter_render: bool = False, **kwargs) -> None:
3301 if plotter_render:
3302 # TODO: should probably be called internally by VTK when plot data or axis
3303 # behavior/logscale is changed?
3304 self.RecalculateBounds()
3305 super()._render_event(*args, plotter_render=plotter_render, **kwargs)
3306
3307 def _add_plot(self, plot_type, *args, **kwargs):
3308 """Add a plot of the given type to this chart."""
3309 plot = self.PLOT_TYPES[plot_type](self, *args, **kwargs)
3310 self.AddPlot(plot)
3311 self._plots[plot_type].append(plot)
3312 return plot
3313
3314 @classmethod
3315 def _parse_format(cls, fmt):
3316 """Parse a format string and separate it into a marker style, line style and color.
3317
3318 Parameters
3319 ----------
3320 fmt : str
3321 Format string to parse. A format string consists of any
3322 combination of a valid marker style, a valid line style
3323 and parsable color. The specific order does not
3324 matter. See :attr:`pyvista.ScatterPlot2D.MARKER_STYLES`
3325 for a list of valid marker styles,
3326 :attr:`pyvista.Pen.LINE_STYLES` for a list of valid line
3327 styles and :class:`pyvista.Color` for an overview of
3328 parsable colors.
3329
3330 Returns
3331 -------
3332 marker_style : str
3333 Extracted marker style (empty string if no marker style
3334 was present in the format string).
3335
3336 line_style : str
3337 Extracted line style (empty string if no line style was
3338 present in the format string).
3339
3340 color : str
3341 Extracted color string (defaults to ``"b"`` if no color
3342 was present in the format string).
3343
3344 Examples
3345 --------
3346 >>> import pyvista as pv
3347 >>> m, l, c = pv.Chart2D._parse_format('x--b')
3348
3349 """
3350 marker_style = ''
3351 line_style = ''
3352 color = None
3353 # Note: All colors, marker styles and line styles are sorted in decreasing order of length
3354 # to be able to find the largest match first (e.g. find 'darkred' and '--' first instead
3355 # of 'red' and '-')
3356 colors = sorted(
3357 itertools.chain(_formatted_hex_colors.keys(), _formatted_color_synonyms.keys()),
3358 key=len,
3359 reverse=True,
3360 )
3361 marker_styles = sorted(ScatterPlot2D.MARKER_STYLES.keys(), key=len, reverse=True)
3362 line_styles = sorted(Pen.LINE_STYLES.keys(), key=len, reverse=True)
3363 hex_pattern = '(#|0x)[A-Fa-f0-9]{6}([A-Fa-f0-9]{2})?' # Match RGB(A) hex string
3364 # Extract color from format string
3365 match = re.search(hex_pattern, fmt) # Start with matching hex strings
3366 if match is not None:
3367 color = match.group()
3368 else: # Proceed with matching color strings
3369 for c in colors:
3370 if c in fmt:
3371 color = c
3372 break
3373 if color is not None:
3374 fmt = fmt.replace(color, '', 1) # Remove found color from format string
3375 else:
3376 color = 'b'
3377 # Extract marker style from format string
3378 for style in marker_styles[:-1]: # Last style is empty string
3379 if style in fmt:
3380 marker_style = style
3381 fmt = fmt.replace(
3382 marker_style,
3383 '',
3384 1,
3385 ) # Remove found marker_style from format string
3386 break
3387 # Extract line style from format string
3388 for style in line_styles[:-1]: # Last style is empty string
3389 if style in fmt:
3390 line_style = style
3391 fmt = fmt.replace(line_style, '', 1) # Remove found line_style from format string
3392 break
3393 return marker_style, line_style, color
3394
3395 def plot(self, x, y=None, fmt='-'):
3396 """Matplotlib like plot method.
3397
3398 Parameters
3399 ----------
3400 x : array_like
3401 Values to plot on the X-axis. In case ``y`` is ``None``,
3402 these are the values to plot on the Y-axis instead.
3403
3404 y : array_like, optional
3405 Values to plot on the Y-axis.
3406
3407 fmt : str, default: "-"
3408 A format string, e.g. ``'ro'`` for red circles. See the Notes
3409 section for a full description of the format strings.
3410
3411 Returns
3412 -------
3413 scatter_plot : plotting.charts.ScatterPlot2D, optional
3414 The created scatter plot when a valid marker style
3415 was present in the format string, ``None`` otherwise.
3416
3417 line_plot : plotting.charts.LinePlot2D, optional
3418 The created line plot when a valid line style was
3419 present in the format string, ``None`` otherwise.
3420
3421 Notes
3422 -----
3423 This plot method shares many of the same plotting features as
3424 the `matplotlib.pyplot.plot
3425 <https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html>`_.
3426 Please reference the documentation there for a full
3427 description of the allowable format strings.
3428
3429 Examples
3430 --------
3431 Generate a line plot.
3432
3433 .. pyvista-plot::
3434 :force_static:
3435
3436 >>> import pyvista as pv
3437 >>> chart = pv.Chart2D()
3438 >>> _, line_plot = chart.plot(range(10), range(10))
3439 >>> chart.show()
3440
3441 Generate a line and scatter plot.
3442
3443 >>> chart = pv.Chart2D()
3444 >>> scatter_plot, line_plot = chart.plot(range(10), fmt='o-')
3445 >>> chart.show()
3446
3447 """
3448 if y is None:
3449 y = x
3450 x = np.arange(len(y))
3451 elif isinstance(y, str):
3452 fmt = y
3453 y = x
3454 x = np.arange(len(y))
3455 marker_style, line_style, color = self._parse_format(fmt)
3456 scatter_plot, line_plot = None, None
3457 if marker_style != '':
3458 scatter_plot = self.scatter(x, y, color=color, style=marker_style)
3459 if line_style != '':
3460 line_plot = self.line(x, y, color=color, style=line_style)
3461 return scatter_plot, line_plot
3462
3463 @_deprecate_positional_args(allowed=['x', 'y'])
3464 def scatter(self, x, y, color='b', size=10, style='o', label=''): # noqa: PLR0917
3465 """Add a scatter plot to this chart.
3466
3467 Parameters
3468 ----------
3469 x : array_like
3470 X coordinates of the points to draw.
3471
3472 y : array_like
3473 Y coordinates of the points to draw.
3474
3475 color : ColorLike, default: "b"
3476 Color of the points drawn in this plot. Any color parsable
3477 by :class:`pyvista.Color` is allowed.
3478
3479 size : float, default: 10
3480 Size of the point markers drawn in this plot.
3481
3482 style : str, default: "o"
3483 Style of the point markers drawn in this plot. See
3484 :ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
3485 for a list of allowed marker styles.
3486
3487 label : str, default: ""
3488 Label of this plot, as shown in the chart's legend.
3489
3490 Returns
3491 -------
3492 plotting.charts.ScatterPlot2D
3493 The created scatter plot.
3494
3495 Examples
3496 --------
3497 Generate a scatter plot.
3498
3499 .. pyvista-plot::
3500 :force_static:
3501
3502 >>> import pyvista as pv
3503 >>> chart = pv.Chart2D()
3504 >>> plot = chart.scatter([0, 1, 2], [2, 1, 3])
3505 >>> chart.show()
3506
3507 """
3508 return self._add_plot('scatter', x, y, color=color, size=size, style=style, label=label)
3509
3510 @_deprecate_positional_args(allowed=['x', 'y'])
3511 def line(self, x, y, color='b', width=1.0, style='-', label=''): # noqa: PLR0917
3512 """Add a line plot to this chart.
3513
3514 Parameters
3515 ----------
3516 x : array_like
3517 X coordinates of the points through which a line should be drawn.
3518
3519 y : array_like
3520 Y coordinates of the points through which a line should be drawn.
3521
3522 color : ColorLike, default: "b"
3523 Color of the line drawn in this plot. Any color parsable
3524 by :class:`pyvista.Color` is allowed.
3525
3526 width : float, default: 1
3527 Width of the line drawn in this plot.
3528
3529 style : str, default: "-"
3530 Style of the line drawn in this plot. See
3531 :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of
3532 allowed line styles.
3533
3534 label : str, default: ""
3535 Label of this plot, as shown in the chart's legend.
3536
3537 Returns
3538 -------
3539 plotting.charts.LinePlot2D
3540 The created line plot.
3541
3542 Examples
3543 --------
3544 Generate a line plot.
3545
3546 .. pyvista-plot::
3547 :force_static:
3548
3549 >>> import pyvista as pv
3550 >>> chart = pv.Chart2D()
3551 >>> plot = chart.line([0, 1, 2], [2, 1, 3])
3552 >>> chart.show()
3553
3554 """
3555 return self._add_plot('line', x, y, color=color, width=width, style=style, label=label)
3556
3557 @_deprecate_positional_args(allowed=['x', 'y1', 'y2'])
3558 def area( # noqa: PLR0917
3559 self, x, y1, y2=None, color='b', label=''
3560 ):
3561 """Add an area plot to this chart.
3562
3563 Parameters
3564 ----------
3565 x : array_like
3566 X coordinates of the points outlining the area to draw.
3567
3568 y1 : array_like
3569 Y coordinates of the points on the first outline of the area to draw.
3570
3571 y2 : array_like, optional
3572 Y coordinates of the points on the second outline of the
3573 area to draw. Defaults to ``np.zeros_like(x)``.
3574
3575 color : ColorLike, default: "b"
3576 Color of the area drawn in this plot. Any color parsable
3577 by :class:`pyvista.Color` is allowed.
3578
3579 label : str, default: ""
3580 Label of this plot, as shown in the chart's legend.
3581
3582 Returns
3583 -------
3584 plotting.charts.AreaPlot
3585 The created area plot.
3586
3587 Examples
3588 --------
3589 Generate an area plot.
3590
3591 .. pyvista-plot::
3592 :force_static:
3593
3594 >>> import pyvista as pv
3595 >>> chart = pv.Chart2D()
3596 >>> plot = chart.area([0, 1, 2], [2, 1, 3])
3597 >>> chart.show()
3598
3599 """
3600 return self._add_plot('area', x, y1, y2, color=color, label=label)
3601
3602 @_deprecate_positional_args(allowed=['x', 'y'])
3603 def bar( # noqa: PLR0917
3604 self, x, y, color=None, orientation='V', label=None
3605 ):
3606 """Add a bar plot to this chart.
3607
3608 Parameters
3609 ----------
3610 x : array_like
3611 Positions (along the x-axis for a vertical orientation,
3612 along the y-axis for a horizontal orientation) of the bars
3613 to draw.
3614
3615 y : array_like
3616 Size of the bars to draw. Multiple bars can be stacked by
3617 passing a sequence of sequences.
3618
3619 color : ColorLike, default: "b"
3620 Color of the bars drawn in this plot. Any color parsable
3621 by :class:`pyvista.Color` is allowed.
3622
3623 orientation : str, default: "V"
3624 Orientation of the bars drawn in this plot. Either ``"H"``
3625 for an horizontal orientation or ``"V"`` for a vertical
3626 orientation.
3627
3628 label : str, default: ""
3629 Label of this plot, as shown in the chart's legend.
3630
3631 Returns
3632 -------
3633 plotting.charts.BarPlot
3634 The created bar plot.
3635
3636 Examples
3637 --------
3638 Generate a bar plot.
3639
3640 .. pyvista-plot::
3641 :force_static:
3642
3643 >>> import pyvista as pv
3644 >>> chart = pv.Chart2D()
3645 >>> plot = chart.bar([0, 1, 2], [2, 1, 3])
3646 >>> chart.show()
3647
3648 """
3649 return self._add_plot('bar', x, y, color=color, orientation=orientation, label=label)
3650
3651 @_deprecate_positional_args(allowed=['x', 'ys'])
3652 def stack( # noqa: PLR0917
3653 self, x, ys, colors=None, labels=None
3654 ):
3655 """Add a stack plot to this chart.
3656
3657 Parameters
3658 ----------
3659 x : array_like
3660 X coordinates of the points outlining the stacks (areas) to draw.
3661
3662 ys : sequence[array_like]
3663 Size of the stacks (areas) to draw at the corresponding X
3664 coordinates. Each sequence defines the sizes of one stack
3665 (area), which are stacked on top of each other.
3666
3667 colors : sequence[ColorLike], optional
3668 Color of the stacks (areas) drawn in this plot. Any color
3669 parsable by :class:`pyvista.Color` is allowed.
3670
3671 labels : sequence[str], default: []
3672 Label for each stack (area) drawn in this plot, as shown
3673 in the chart's legend.
3674
3675 Returns
3676 -------
3677 plotting.charts.StackPlot
3678 The created stack plot.
3679
3680 Examples
3681 --------
3682 Generate a stack plot.
3683
3684 .. pyvista-plot::
3685 :force_static:
3686
3687 >>> import pyvista as pv
3688 >>> chart = pv.Chart2D()
3689 >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 1]])
3690 >>> chart.show()
3691
3692 """
3693 return self._add_plot('stack', x, ys, colors=colors, labels=labels)
3694
3695 def plots(self, plot_type=None):
3696 """Return all plots of the specified type in this chart.
3697
3698 Parameters
3699 ----------
3700 plot_type : str, optional
3701 The type of plots to return. Allowed types are
3702 ``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
3703 and ``"stack"``.
3704 If no type is provided (``None``), all plots are returned,
3705 regardless of their type.
3706
3707 Yields
3708 ------
3709 plot
3710 One of the plots (of the specified type) in this chart.
3711
3712 Examples
3713 --------
3714 Create a 2D chart with a line and scatter plot.
3715
3716 .. pyvista-plot::
3717 :force_static:
3718
3719 >>> import pyvista as pv
3720 >>> chart = pv.Chart2D()
3721 >>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], 'o-')
3722 >>> chart.show()
3723
3724 Retrieve all plots in the chart.
3725
3726 >>> plots = [*chart.plots()]
3727 >>> scatter_plot in plots and line_plot in plots
3728 True
3729
3730 Retrieve all line plots in the chart.
3731
3732 >>> line_plots = [*chart.plots('line')]
3733 >>> line_plot == line_plots[0]
3734 True
3735
3736 """
3737 plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
3738 for pl_type in plot_types:
3739 yield from self._plots[pl_type]
3740
3741 def remove_plot(self, plot: ScatterPlot2D | LinePlot2D | AreaPlot | BarPlot | StackPlot):
3742 """Remove the given plot from this chart.
3743
3744 Parameters
3745 ----------
3746 plot
3747 The plot to remove.
3748
3749 Examples
3750 --------
3751 Create a 2D chart with a line and scatter plot.
3752
3753 .. pyvista-plot::
3754 :force_static:
3755
3756 >>> import pyvista as pv
3757 >>> chart = pv.Chart2D()
3758 >>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], 'o-')
3759 >>> chart.show()
3760
3761 Remove the scatter plot from the chart.
3762
3763 >>> chart.remove_plot(scatter_plot)
3764 >>> chart.show()
3765
3766 """
3767 try:
3768 plot_type = self._PLOT_CLASSES[type(plot)]
3769 self._plots[plot_type].remove(plot)
3770 self.RemovePlotInstance(plot)
3771 except (KeyError, ValueError):
3772 msg = 'The given plot is not part of this chart.'
3773 raise ValueError(msg)
3774
3775 def clear(self, plot_type=None) -> None:
3776 """Remove all plots of the specified type from this chart.
3777
3778 Parameters
3779 ----------
3780 plot_type : str, optional
3781 The type of the plots to remove. Allowed types are
3782 ``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
3783 and ``"stack"``.
3784
3785 If no type is provided (``None``), all plots are removed,
3786 regardless of their type.
3787
3788 Examples
3789 --------
3790 Create a 2D chart with multiple line and scatter plot.
3791
3792 .. pyvista-plot::
3793 :force_static:
3794
3795 >>> import pyvista as pv
3796 >>> chart = pv.Chart2D()
3797 >>> _ = chart.plot([0, 1, 2], [2, 1, 3], 'o-b')
3798 >>> _ = chart.plot([-2, -1, 0], [3, 1, 2], 'd-r')
3799 >>> chart.show()
3800
3801 Remove all scatter plots from the chart.
3802
3803 >>> chart.clear('scatter')
3804 >>> chart.show()
3805
3806 """
3807 plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
3808 for pl_type in plot_types:
3809 # Make a copy, as this list will be modified by remove_plot
3810 plots = [*self._plots[pl_type]]
3811 for plot in plots:
3812 self.remove_plot(plot)
3813
3814 @property
3815 def x_axis(self): # numpydoc ignore=RT01
3816 """Return this chart's horizontal (x) :class:`Axis <plotting.charts.Axis>`.
3817
3818 Examples
3819 --------
3820 Create a 2D plot and hide the x-axis.
3821
3822 .. pyvista-plot::
3823 :force_static:
3824
3825 >>> import pyvista as pv
3826 >>> chart = pv.Chart2D()
3827 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
3828 >>> chart.x_axis.toggle()
3829 >>> chart.show()
3830
3831 """
3832 return self._x_axis
3833
3834 @property
3835 def y_axis(self): # numpydoc ignore=RT01
3836 """Return this chart's vertical (y) :class:`Axis <plotting.charts.Axis>`.
3837
3838 Examples
3839 --------
3840 Create a 2D plot and hide the y-axis.
3841
3842 .. pyvista-plot::
3843 :force_static:
3844
3845 >>> import pyvista as pv
3846 >>> chart = pv.Chart2D()
3847 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
3848 >>> chart.y_axis.toggle()
3849 >>> chart.show()
3850
3851 """
3852 return self._y_axis
3853
3854 @property
3855 def x_label(self): # numpydoc ignore=RT01
3856 """Return or set the label of this chart's x-axis.
3857
3858 Examples
3859 --------
3860 Create a 2D plot and set custom axis labels.
3861
3862 .. pyvista-plot::
3863 :force_static:
3864
3865 >>> import pyvista as pv
3866 >>> chart = pv.Chart2D()
3867 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
3868 >>> chart.x_label = 'Horizontal axis'
3869 >>> chart.y_label = 'Vertical axis'
3870 >>> chart.show()
3871
3872 """
3873 return self.x_axis.label
3874
3875 @x_label.setter
3876 def x_label(self, val) -> None:
3877 self.x_axis.label = val
3878
3879 @property
3880 def y_label(self): # numpydoc ignore=RT01
3881 """Return or set the label of this chart's y-axis.
3882
3883 Examples
3884 --------
3885 Create a 2D plot and set custom axis labels.
3886
3887 .. pyvista-plot::
3888 :force_static:
3889
3890 >>> import pyvista as pv
3891 >>> chart = pv.Chart2D()
3892 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
3893 >>> chart.x_label = 'Horizontal axis'
3894 >>> chart.y_label = 'Vertical axis'
3895 >>> chart.show()
3896
3897 """
3898 return self.y_axis.label
3899
3900 @y_label.setter
3901 def y_label(self, val) -> None:
3902 self.y_axis.label = val
3903
3904 @property
3905 def x_range(self): # numpydoc ignore=RT01
3906 """Return or set the range of this chart's x-axis.
3907
3908 Examples
3909 --------
3910 Create a 2D plot and set custom axis ranges.
3911
3912 .. pyvista-plot::
3913 :force_static:
3914
3915 >>> import pyvista as pv
3916 >>> chart = pv.Chart2D()
3917 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
3918 >>> chart.x_range = [-2, 2]
3919 >>> chart.y_range = [0, 5]
3920 >>> chart.show()
3921
3922 """
3923 return self.x_axis.range
3924
3925 @x_range.setter
3926 def x_range(self, val) -> None:
3927 self.x_axis.range = val
3928
3929 @property
3930 def y_range(self): # numpydoc ignore=RT01
3931 """Return or set the range of this chart's y-axis.
3932
3933 Examples
3934 --------
3935 Create a 2D plot and set custom axis ranges.
3936
3937 .. pyvista-plot::
3938 :force_static:
3939
3940 >>> import pyvista as pv
3941 >>> chart = pv.Chart2D()
3942 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
3943 >>> chart.x_range = [-2, 2]
3944 >>> chart.y_range = [0, 5]
3945 >>> chart.show()
3946
3947 """
3948 return self.y_axis.range
3949
3950 @y_range.setter
3951 def y_range(self, val) -> None:
3952 self.y_axis.range = val
3953
3954 @property
3955 def grid(self): # numpydoc ignore=RT01
3956 """Enable or disable the chart grid.
3957
3958 Examples
3959 --------
3960 Create a 2D chart with the grid disabled.
3961
3962 .. pyvista-plot::
3963 :force_static:
3964
3965 >>> import pyvista as pv
3966 >>> import numpy as np
3967 >>> x = np.linspace(0, 2 * np.pi, 20)
3968 >>> y = np.sin(x)
3969 >>> chart = pv.Chart2D()
3970 >>> _ = chart.line(x, y, color='r')
3971 >>> chart.grid = False
3972 >>> chart.show()
3973
3974 Enable the grid
3975
3976 >>> chart.grid = True
3977 >>> chart.show()
3978
3979 """
3980 return self.x_axis.grid and self.y_axis.grid
3981
3982 @grid.setter
3983 def grid(self, val) -> None:
3984 self.x_axis.grid = val
3985 self.y_axis.grid = val
3986
3987 def hide_axes(self) -> None:
3988 """Hide the x- and y-axis of this chart.
3989
3990 This includes all labels, ticks and the grid.
3991
3992 Examples
3993 --------
3994 Create a 2D plot and hide the axes.
3995
3996 .. pyvista-plot::
3997 :force_static:
3998
3999 >>> import pyvista as pv
4000 >>> chart = pv.Chart2D()
4001 >>> _ = chart.line([0, 1, 2], [2, 1, 3])
4002 >>> chart.hide_axes()
4003 >>> chart.show()
4004
4005 """
4006 for axis in (self.x_axis, self.y_axis):
4007 axis.visible = False
4008 axis.label_visible = False
4009 axis.ticks_visible = False
4010 axis.tick_labels_visible = False
4011 axis.grid = False
4012
4013
4014 class BoxPlot(_NoNewAttrMixin, DisableVtkSnakeCase, _MultiCompPlot, _vtk.vtkPlotBox):
4015 """Class representing a box plot.
4016
4017 Users should typically not directly create new plot instances, but
4018 use the dedicated ``ChartBox`` class.
4019
4020 Parameters
4021 ----------
4022 chart : ChartBox
4023 The chart containing this plot.
4024
4025 data : sequence[array_like]
4026 Dataset(s) from which the relevant statistics will be
4027 calculated used to draw the box plot.
4028
4029 colors : sequence[ColorLike], optional
4030 Color of the boxes drawn in this plot. Any color parsable by
4031 :class:`pyvista.Color` is allowed. If omitted (``None``), the
4032 default color scheme is used.
4033
4034 labels : sequence[str], default: []
4035 Label for each box drawn in this plot, as shown in the chart's
4036 legend.
4037
4038 Examples
4039 --------
4040 Create boxplots for datasets sampled from shifted normal distributions.
4041
4042 .. pyvista-plot::
4043 :force_static:
4044
4045 >>> import pyvista as pv
4046 >>> import numpy as np
4047 >>> rng = np.random.default_rng(
4048 ... 1
4049 ... ) # Seeded random number generator used for data generation
4050 >>> normal_data = [rng.normal(i, size=50) for i in range(5)]
4051 >>> chart = pv.ChartBox(
4052 ... normal_data, labels=[f'x ~ N({i},1)' for i in range(5)]
4053 ... )
4054 >>> chart.show()
4055
4056 """
4057
4058 _DOC_SUBS = { # noqa: RUF012
4059 'plot_name': 'box plot',
4060 'chart_init': 'pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])',
4061 'plot_init': 'chart.plot',
4062 'multichart_init': 'pv.ChartBox('
4063 '[[0, 1, 1, 2, 3, 4, 5], '
4064 '[0, 1, 2, 2, 3, 4, 5], '
4065 '[0, 1, 2, 3, 3, 4, 5], '
4066 '[0, 1, 2, 3, 4, 4, 5]])',
4067 'multiplot_init': 'chart.plot',
4068 }
4069
4070 @_deprecate_positional_args(allowed=['chart', 'data'])
4071 def __init__( # noqa: PLR0917
4072 self, chart, data, colors=None, labels=None
4073 ) -> None:
4074 """Initialize a new box plot instance."""
4075 super().__init__(chart)
4076 self._table = pv.Table(
4077 {f'data_{i}': np.asarray(d) for i, d in enumerate(data)},
4078 )
4079 self._quartiles = _vtk.vtkComputeQuartiles()
4080 self._quartiles.SetInputData(self._table)
4081 self.SetInputData(self._quartiles.GetOutput())
4082 self.update(data)
4083 self.SetLookupTable(self._lookup_table)
4084 self.colors = colors
4085 self.labels = labels
4086
4087 @property
4088 def data(self): # numpydoc ignore=RT01
4089 """Retrieve the datasets of which the boxplots are drawn.
4090
4091 Examples
4092 --------
4093 Create a box plot and display the datasets.
4094
4095 .. pyvista-plot::
4096 :force_static:
4097
4098 >>> import pyvista as pv
4099 >>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
4100 >>> chart.plot.data
4101 (pyvista_ndarray([0, 1, 1, 2, 3, 3, 4]),)
4102 >>> chart.show()
4103
4104 """
4105 return tuple(self._table[f'data_{i}'] for i in range(self._table.n_arrays))
4106
4107 @property
4108 def stats(self): # numpydoc ignore=RT01
4109 """Retrieve the statistics of the datasets of which the boxplots are drawn.
4110
4111 The statistics are the quartiles and extremum values.
4112
4113 Examples
4114 --------
4115 Create a box plot and display the statistics.
4116
4117 .. pyvista-plot::
4118 :force_static:
4119
4120 >>> import pyvista as pv
4121 >>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
4122 >>> chart.plot.stats
4123 (pyvista_ndarray([0., 1., 2., 3., 4.]),)
4124 >>> chart.show()
4125
4126 """
4127 stats_table = pv.Table(self._quartiles.GetOutput())
4128 return tuple(stats_table[f'data_{i}'] for i in range(stats_table.n_arrays))
4129
4130 def update(self, data) -> None:
4131 """Update the plot's underlying dataset(s).
4132
4133 Parameters
4134 ----------
4135 data : sequence[array_like]
4136 The new dataset(s) used in this box plot.
4137
4138 Examples
4139 --------
4140 Create a box plot from a standard Gaussian dataset.
4141
4142 .. pyvista-plot::
4143 :force_static:
4144
4145 >>> import pyvista as pv
4146 >>> import numpy as np
4147 >>> rng = np.random.default_rng(
4148 ... 1
4149 ... ) # Seeded random number generator for data generation
4150 >>> chart = pv.ChartBox([rng.normal(size=100)])
4151 >>> chart.show()
4152
4153 Update the box plot (shift the standard Gaussian distribution).
4154
4155 >>> chart.plot.update([rng.normal(loc=2, size=100)])
4156 >>> chart.show()
4157
4158 """
4159 self._table.update({f'data_{i}': np.asarray(d) for i, d in enumerate(data)})
4160 self._quartiles.Update()
4161
4162
4163 class ChartBox(_NoNewAttrMixin, DisableVtkSnakeCase, _Chart, _vtk.vtkChartBox):
4164 """Dedicated chart for drawing box plots.
4165
4166 Parameters
4167 ----------
4168 data : sequence[array_like]
4169 Dataset(s) from which the relevant statistics will be
4170 calculated used to draw the box plot.
4171
4172 colors : sequence[ColorLike], optional
4173 Color used for each drawn boxplot. If omitted (``None``), the
4174 default color scheme is used.
4175
4176 labels : sequence[str], default: []
4177 Label for each drawn boxplot, as shown in the chart's
4178 legend.
4179
4180 size : sequence[float], optional
4181 Size of the chart in normalized coordinates. A size of ``(0,
4182 0)`` is invisible, a size of ``(1, 1)`` occupies the whole
4183 renderer's width and height.
4184
4185 loc : sequence[float], optional
4186 Location of the chart (its bottom left corner) in normalized
4187 coordinates. A location of ``(0, 0)`` corresponds to the
4188 renderer's bottom left corner, a location of ``(1, 1)``
4189 corresponds to the renderer's top right corner.
4190
4191 Examples
4192 --------
4193 Create boxplots for datasets sampled from shifted normal distributions.
4194
4195 .. pyvista-plot::
4196 :force_static:
4197
4198 >>> import pyvista as pv
4199 >>> import numpy as np
4200 >>> rng = np.random.default_rng(
4201 ... 1
4202 ... ) # Seeded random number generator used for data generation
4203 >>> normal_data = [rng.normal(i, size=50) for i in range(5)]
4204 >>> chart = pv.ChartBox(
4205 ... normal_data, labels=[f'x ~ N({i},1)' for i in range(5)]
4206 ... )
4207 >>> chart.show()
4208
4209 """
4210
4211 _DOC_SUBS = { # noqa: RUF012
4212 'chart_name': 'boxplot chart',
4213 'chart_args': '[[0, 1, 1, 2, 3, 3, 4]]',
4214 'chart_init': '',
4215 'chart_set_labels': 'chart.plot.label = "Data label"',
4216 }
4217
4218 @_deprecate_positional_args(allowed=['data'])
4219 def __init__( # noqa: PLR0917
4220 self,
4221 data,
4222 colors=None,
4223 labels=None,
4224 size=None,
4225 loc=None,
4226 ) -> None: # numpydoc ignore=PR01,RT01
4227 """Initialize a new chart containing box plots."""
4228 self.SetAutoSize(False) # We manually set the appropriate size
4229 if size is None:
4230 size = (1, 1)
4231 if loc is None:
4232 loc = (0, 0)
4233 super().__init__(size, loc)
4234 self._plot = BoxPlot(self, data, colors=colors, labels=labels)
4235 self.SetPlot(self._plot)
4236 self.SetColumnVisibilityAll(True)
4237 self.legend_visible = True
4238
4239 def _render_event(self, *args, **kwargs) -> None:
4240 super()._render_event(*args, **kwargs)
4241
4242 @property
4243 def _geometry(self):
4244 return _Chart._geometry.fget(self) # type: ignore[attr-defined]
4245
4246 @_geometry.setter
4247 def _geometry(self, value):
4248 _Chart._geometry.fset(self, value) # type: ignore[attr-defined]
4249
4250 @property
4251 def plot(self): # numpydoc ignore=RT01
4252 """Return the :class:`~plotting.charts.BoxPlot` instance associated with this chart.
4253
4254 Examples
4255 --------
4256 Create a box plot from a standard Gaussian dataset.
4257
4258 .. pyvista-plot::
4259 :force_static:
4260
4261 >>> import pyvista as pv
4262 >>> import numpy as np
4263 >>> rng = np.random.default_rng(
4264 ... 1
4265 ... ) # Seeded random number generator for data generation
4266 >>> chart = pv.ChartBox([rng.normal(size=100)])
4267 >>> chart.show()
4268
4269 Update the box plot (shift the standard Gaussian distribution).
4270
4271 >>> chart.plot.update([rng.normal(loc=2, size=100)])
4272 >>> chart.show()
4273
4274 """
4275 return self._plot
4276
4277 @property
4278 def size(self): # numpydoc ignore=RT01
4279 """Return or set the chart size in normalized coordinates.
4280
4281 A size of ``(1, 1)`` occupies the whole renderer.
4282
4283 Notes
4284 -----
4285 Customisable ChartBox geometry is only supported in VTK v9.2
4286 or newer. For older VTK versions, the size cannot be modified,
4287 filling up the entire viewport by default.
4288
4289 Examples
4290 --------
4291 Create a half-sized boxplot chart centered in the middle of the
4292 renderer.
4293
4294 .. pyvista-plot::
4295 :force_static:
4296
4297 >>> import pyvista as pv
4298 >>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
4299 >>> chart.size = (0.5, 0.5)
4300 >>> chart.loc = (0.25, 0.25)
4301 >>> chart.show()
4302
4303 """
4304 return _Chart.size.fget(self) # type: ignore[attr-defined]
4305
4306 @size.setter
4307 def size(self, val):
4308 _Chart.size.fset(self, val) # type: ignore[attr-defined]
4309
4310 @property
4311 def loc(self): # numpydoc ignore=RT01
4312 """Return or set the chart position in normalized coordinates.
4313
4314 This denotes the location of the chart's bottom left corner.
4315
4316 Notes
4317 -----
4318 Customisable ChartBox geometry is only supported in VTK v9.2
4319 or newer. For older VTK versions, the location cannot be modified,
4320 filling up the entire viewport by default.
4321
4322 Examples
4323 --------
4324 Create a half-sized boxplot chart centered in the middle of the
4325 renderer.
4326
4327 .. pyvista-plot::
4328 :force_static:
4329
4330 >>> import pyvista as pv
4331 >>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
4332 >>> chart.size = (0.5, 0.5)
4333 >>> chart.loc = (0.25, 0.25)
4334 >>> chart.show()
4335
4336 """
4337 return _Chart.loc.fget(self) # type: ignore[attr-defined]
4338
4339 @loc.setter
4340 def loc(self, val):
4341 _Chart.loc.fset(self, val) # type: ignore[attr-defined]
4342
4343
4344 class PiePlot(_MultiCompPlot, _vtkWrapper, _vtk.vtkPlotPie):
4345 """Class representing a pie plot.
4346
4347 Users should typically not directly create new plot instances, but
4348 use the dedicated :class:`ChartPie` class.
4349
4350 Parameters
4351 ----------
4352 chart : ChartPie
4353 The chart containing this plot.
4354
4355 data : array_like
4356 Relative size of each pie segment.
4357
4358 colors : sequence[ColorLike], optional
4359 Color of the segments drawn in this plot. Any color parsable
4360 by :class:`pyvista.Color` is allowed. If omitted (``None``),
4361 the default color scheme is used.
4362
4363 labels : sequence[str], default: []
4364 Label for each pie segment drawn in this plot, as shown in the
4365 chart's legend.
4366
4367 Examples
4368 --------
4369 Create a pie plot showing the usage of tax money.
4370
4371 .. pyvista-plot::
4372 :force_static:
4373
4374 >>> import pyvista as pv
4375 >>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
4376 >>> l = [
4377 ... 'Social benefits',
4378 ... 'Governance',
4379 ... 'Economic policy',
4380 ... 'Education',
4381 ... 'Other',
4382 ... ]
4383 >>> chart = pv.ChartPie(x, labels=l)
4384 >>> chart.show()
4385
4386 """
4387
4388 _DOC_SUBS = { # noqa: RUF012
4389 'plot_name': 'pie plot',
4390 'chart_init': 'pv.ChartPie([4, 3, 2, 1])',
4391 'plot_init': 'chart.plot',
4392 'multichart_init': 'pv.ChartPie([4, 3, 2, 1])',
4393 'multiplot_init': 'chart.plot',
4394 }
4395
4396 @_deprecate_positional_args(allowed=['chart', 'data'])
4397 def __init__( # noqa: PLR0917
4398 self, chart, data, colors=None, labels=None
4399 ) -> None:
4400 """Initialize a new pie plot instance."""
4401 super().__init__(chart)
4402 self._table = pv.Table(data)
4403 self.SetInputData(self._table)
4404 self.SetInputArray(0, self._table.keys()[0])
4405 self.update(data)
4406
4407 self.labels = labels
4408
4409 self.SetColorSeries(self._color_series)
4410 self.colors = colors
4411
4412 @property
4413 def data(self): # numpydoc ignore=RT01
4414 """Retrieve the sizes of the drawn segments.
4415
4416 Examples
4417 --------
4418 Create a pie plot and display the sizes.
4419
4420 .. pyvista-plot::
4421 :force_static:
4422
4423 >>> import pyvista as pv
4424 >>> chart = pv.ChartPie([1, 2, 3])
4425 >>> chart.plot.data
4426 pyvista_ndarray([1, 2, 3])
4427 >>> chart.show()
4428
4429 """
4430 return self._table[0]
4431
4432 def update(self, data) -> None:
4433 """Update the size of the pie segments.
4434
4435 Parameters
4436 ----------
4437 data : array_like
4438 The new relative size of each pie segment.
4439
4440 Examples
4441 --------
4442 Create a pie plot with segments of increasing size.
4443
4444 .. pyvista-plot::
4445 :force_static:
4446
4447 >>> import pyvista as pv
4448 >>> chart = pv.ChartPie([1, 2, 3, 4, 5])
4449 >>> chart.show()
4450
4451 Update the pie plot (segments of equal size).
4452
4453 >>> chart.plot.update([1, 1, 1, 1, 1])
4454 >>> chart.show()
4455
4456 """
4457 self._table.update(data)
4458
4459
4460 class ChartPie(_NoNewAttrMixin, DisableVtkSnakeCase, _Chart, _vtk.vtkChartPie):
4461 """Dedicated chart for drawing pie plots.
4462
4463 Parameters
4464 ----------
4465 data : array_like
4466 Relative size of each pie segment.
4467
4468 colors : sequence[ColorLike], optional
4469 Color used for each pie segment drawn in this plot. If
4470 omitted (``None``), the default color scheme is used.
4471
4472 labels : sequence[str], default: []
4473 Label for each pie segment drawn in this plot, as shown in the
4474 chart's legend.
4475
4476 size : sequence[float], optional
4477 Size of the chart in normalized coordinates. A size of ``(0,
4478 0)`` is invisible, a size of ``(1, 1)`` occupies the whole
4479 renderer's width and height.
4480
4481 loc : sequence[float], optional
4482 Location of the chart (its bottom left corner) in normalized
4483 coordinates. A location of ``(0, 0)`` corresponds to the
4484 renderer's bottom left corner, a location of ``(1, 1)``
4485 corresponds to the renderer's top right corner.
4486
4487 Examples
4488 --------
4489 Create a pie plot showing the usage of tax money.
4490
4491 .. pyvista-plot::
4492 :force_static:
4493
4494 >>> import pyvista as pv
4495 >>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
4496 >>> l = [
4497 ... 'Social benefits',
4498 ... 'Governance',
4499 ... 'Economic policy',
4500 ... 'Education',
4501 ... 'Other',
4502 ... ]
4503 >>> chart = pv.ChartPie(x, labels=l)
4504 >>> chart.show()
4505
4506 """
4507
4508 _DOC_SUBS = { # noqa: RUF012
4509 'chart_name': 'pie chart',
4510 'chart_args': '[5, 4, 3, 2, 1]',
4511 'chart_init': '',
4512 'chart_set_labels': 'chart.plot.labels = ["A", "B", "C", "D", "E"]',
4513 }
4514
4515 @_deprecate_positional_args(allowed=['data'])
4516 def __init__( # noqa: PLR0917
4517 self,
4518 data,
4519 colors=None,
4520 labels=None,
4521 size=None,
4522 loc=None,
4523 ) -> None: # numpydoc ignore=PR01,RT01
4524 """Initialize a new chart containing a pie plot."""
4525 self.SetAutoSize(False) # We manually set the appropriate size
4526 if size is None:
4527 size = (1, 1)
4528 if loc is None:
4529 loc = (0, 0)
4530 super().__init__(size, loc)
4531 self._plot = PiePlot(self, data, colors=colors, labels=labels)
4532 self.SetPlot(self._plot)
4533 self.legend_visible = True
4534
4535 def _render_event(self, *args, **kwargs) -> None:
4536 super()._render_event(*args, **kwargs)
4537
4538 @property
4539 def _geometry(self):
4540 return _Chart._geometry.fget(self) # type: ignore[attr-defined]
4541
4542 @_geometry.setter
4543 def _geometry(self, value):
4544 _Chart._geometry.fset(self, value) # type: ignore[attr-defined]
4545
4546 @property
4547 def plot(self): # numpydoc ignore=RT01
4548 """Return the :class:`~plotting.charts.PiePlot` instance associated with this chart.
4549
4550 Examples
4551 --------
4552 Create a pie plot with segments of increasing size.
4553
4554 .. pyvista-plot::
4555 :force_static:
4556
4557 >>> import pyvista as pv
4558 >>> chart = pv.ChartPie([1, 2, 3, 4, 5])
4559 >>> chart.show()
4560
4561 Update the pie plot (segments of equal size).
4562
4563 >>> chart.plot.update([1, 1, 1, 1, 1])
4564 >>> chart.show()
4565
4566 """
4567 return self._plot
4568
4569 @property
4570 def size(self): # numpydoc ignore=RT01
4571 """Return or set the chart size in normalized coordinates.
4572
4573 A size of ``(1, 1)`` occupies the whole renderer.
4574
4575 Notes
4576 -----
4577 Customisable ChartPie geometry is only supported in VTK v9.2
4578 or newer. For older VTK versions, the size cannot be modified,
4579 filling up the entire viewport by default.
4580
4581 Examples
4582 --------
4583 Create a half-sized pie chart centered in the middle of the
4584 renderer.
4585
4586 .. pyvista-plot::
4587 :force_static:
4588
4589 >>> import pyvista as pv
4590 >>> chart = pv.ChartPie([5, 4, 3, 2, 1])
4591 >>> chart.size = (0.5, 0.5)
4592 >>> chart.loc = (0.25, 0.25)
4593 >>> chart.show()
4594
4595 """
4596 return _Chart.size.fget(self) # type: ignore[attr-defined]
4597
4598 @size.setter
4599 def size(self, val):
4600 _Chart.size.fset(self, val) # type: ignore[attr-defined]
4601
4602 @property
4603 def loc(self): # numpydoc ignore=RT01
4604 """Return or set the chart position in normalized coordinates.
4605
4606 This denotes the location of the chart's bottom left corner.
4607
4608 Notes
4609 -----
4610 Customisable ChartPie geometry is only supported in VTK v9.2
4611 or newer. For older VTK versions, the location cannot be modified,
4612 filling up the entire viewport by default.
4613
4614 Examples
4615 --------
4616 Create a half-sized pie chart centered in the middle of the
4617 renderer.
4618
4619 .. pyvista-plot::
4620 :force_static:
4621
4622 >>> import pyvista as pv
4623 >>> chart = pv.ChartPie([5, 4, 3, 2, 1])
4624 >>> chart.size = (0.5, 0.5)
4625 >>> chart.loc = (0.25, 0.25)
4626 >>> chart.show()
4627
4628 """
4629 return _Chart.loc.fget(self) # type: ignore[attr-defined]
4630
4631 @loc.setter
4632 def loc(self, val):
4633 _Chart.loc.fset(self, val) # type: ignore[attr-defined]
4634
4635
4636 class ChartMPL(_NoNewAttrMixin, DisableVtkSnakeCase, _Chart, _vtk.vtkImageItem):
4637 """Create new chart from an existing matplotlib figure.
4638
4639 Parameters
4640 ----------
4641 figure : matplotlib.figure.Figure, optional
4642 The matplotlib figure to draw. If no figure is
4643 provided ( ``None`` ), a new figure is created.
4644
4645 size : sequence[float], default: (1, 1)
4646 Size of the chart in normalized coordinates. A size of ``(0,
4647 0)`` is invisible, a size of ``(1, 1)`` occupies the whole
4648 renderer's width and height.
4649
4650 loc : sequence[float], default: (0, 0)
4651 Location of the chart (its bottom left corner) in normalized
4652 coordinates. A location of ``(0, 0)`` corresponds to the
4653 renderer's bottom left corner, a location of ``(1, 1)``
4654 corresponds to the renderer's top right corner.
4655
4656 redraw_on_render : bool, default: True
4657 Flag indicating whether the chart should be redrawn when
4658 the plotter is rendered. For static charts, setting this
4659 to ``False`` can improve performance.
4660
4661 See Also
4662 --------
4663 :ref:`chart_overlays_example`
4664
4665 Examples
4666 --------
4667 Plot streamlines of a vector field with varying colors (based on `this example <https://matplotlib.org/stable/gallery/images_contours_and_fields/plot_streamplot.html>`_).
4668
4669
4670 .. pyvista-plot::
4671 :force_static:
4672
4673 >>> import pyvista as pv
4674 >>> import numpy as np
4675 >>> import matplotlib.pyplot as plt
4676
4677 >>> w = 3
4678 >>> Y, X = np.mgrid[-w:w:100j, -w:w:100j]
4679 >>> U = -1 - X**2 + Y
4680 >>> V = 1 + X - Y**2
4681 >>> speed = np.sqrt(U**2 + V**2)
4682
4683 >>> f, ax = plt.subplots()
4684 >>> strm = ax.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
4685 >>> _ = f.colorbar(strm.lines)
4686 >>> _ = ax.set_title('Streamplot with varying Color')
4687 >>> plt.tight_layout()
4688
4689 >>> chart = pv.ChartMPL(f)
4690 >>> chart.show()
4691
4692 """
4693
4694 _DOC_SUBS = { # noqa: RUF012
4695 'chart_name': 'matplotlib chart',
4696 'chart_args': '',
4697 'chart_init': """
4698 >>> plots = chart.figure.axes[0].plot([0, 1, 2], [2, 1, 3])""",
4699 'chart_set_labels': 'plots[0].label = "My awesome plot"',
4700 }
4701
4702 @_deprecate_positional_args(allowed=['figure'])
4703 def __init__( # noqa: PLR0917
4704 self,
4705 figure=None,
4706 size=(1, 1),
4707 loc=(0, 0),
4708 redraw_on_render: bool = True, # noqa: FBT001, FBT002
4709 ) -> None: # numpydoc ignore=PR01,RT01
4710 """Initialize chart."""
4711 super().__init__(size, loc)
4712 if figure is None:
4713 figure, _ = plt.subplots()
4714 self._fig = figure
4715 self._canvas = FigureCanvasAgg(
4716 self._fig,
4717 ) # Switch backends and store reference to figure's canvas
4718 # Make figure and axes fully transparent, as the background is already dealt with
4719 # by self._background.
4720 self._fig.patch.set_alpha(0)
4721 for ax in self._fig.axes:
4722 ax.patch.set_alpha(0)
4723 self._canvas.mpl_connect('draw_event', self._redraw) # Attach 'draw_event' callback
4724 self._redraw_on_render = redraw_on_render
4725
4726 self._redraw()
4727
4728 # Close the underlying matplotlib figure when creating the sphinx gallery.
4729 # This prevents the charts from being drawn twice in example scripts:
4730 # once as a pyvista plot (fetched by the 'pyvista' scraper) and once as a
4731 # matplotlib figure (fetched by the 'matplotlib' scraper).
4732 # See #1999 and #2031.
4733 if pv.BUILDING_GALLERY: # pragma: no cover
4734 plt.close(self._fig)
4735
4736 @property
4737 def legend(self): # numpydoc ignore=RT01
4738 """Access the legend of the underlying matplotlib axes.
4739
4740 Notes
4741 -----
4742 Unlike :class:`Chart2D`, :class:`ChartBox`, and :class:`ChartPie`,
4743 the legend of a matplotlib-backed chart must be configured through
4744 the matplotlib API on :attr:`figure`.
4745
4746 """
4747 msg = (
4748 'ChartMPL does not expose a VTK legend; configure the legend '
4749 'through the underlying matplotlib figure instead (see `figure`).'
4750 )
4751 raise NotImplementedError(msg)
4752
4753 @property
4754 def figure(self): # numpydoc ignore=RT01
4755 """Retrieve the matplotlib figure associated with this chart.
4756
4757 Examples
4758 --------
4759 Create a matplotlib chart from an existing figure.
4760
4761
4762 .. pyvista-plot::
4763 :force_static:
4764
4765 >>> import pyvista as pv
4766 >>> import matplotlib.pyplot as plt
4767 >>> f, ax = plt.subplots()
4768 >>> _ = ax.plot([0, 1, 2], [2, 1, 3])
4769 >>> chart = pv.ChartMPL(f)
4770 >>> chart.figure is f
4771 True
4772 >>> chart.show()
4773
4774 """
4775 return self._fig
4776
4777 @property
4778 def redraw_on_render(self): # numpydoc ignore=RT01
4779 """Return or set the chart's redraw-on-render behavior.
4780
4781 Notes
4782 -----
4783 When disabled, the chart will only be redrawn when the
4784 Plotter window is resized or the matplotlib figure is
4785 manually redrawn using ``fig.canvas.draw()``.
4786 When enabled, the chart will also be automatically
4787 redrawn whenever the Plotter is rendered using
4788 ``plotter.render()``.
4789
4790 """
4791 return self._redraw_on_render
4792
4793 @redraw_on_render.setter
4794 def redraw_on_render(self, val) -> None:
4795 self._redraw_on_render = bool(val)
4796
4797 def _resize(self):
4798 r_w, r_h = self._renderer.GetSize()
4799 c_w, c_h = (int(s) for s in self._canvas.get_width_height())
4800 # Calculate target size from specified normalized width and height
4801 # and the renderer's current size
4802 t_w = int(self._size[0] * r_w)
4803 t_h = int(self._size[1] * r_h)
4804 resize = c_w != t_w or c_h != t_h
4805 if resize:
4806 # Mismatch between canvas size and target size, so resize figure:
4807 f_w = t_w / self._fig.dpi
4808 f_h = t_h / self._fig.dpi
4809 self._fig.set_size_inches(f_w, f_h)
4810 self.position = (int(self._loc[0] * r_w), int(self._loc[1] * r_h))
4811 return resize
4812
4813 def _redraw(self, event=None) -> None:
4814 """Redraw the chart."""
4815 if event is None:
4816 # Manual call, so make sure canvas is redrawn first (which will callback to _redraw
4817 # with a proper event defined)
4818 self._canvas.draw()
4819 else:
4820 # Called from draw_event callback
4821 img = np.frombuffer(
4822 self._canvas.buffer_rgba(),
4823 dtype=np.uint8,
4824 ) # Store figure data in numpy array
4825 w, h = self._canvas.get_width_height()
4826 img_arr = img.reshape([h, w, 4])
4827 img_data = pv.Texture(img_arr).to_image() # type: ignore[abstract] # Convert to vtkImageData
4828 self.SetImage(img_data)
4829
4830 def _render_event(self, *_, plotter_render: bool = False, **__) -> None:
4831 # Redraw figure when geometry has changed (self._resize call
4832 # already updated figure dimensions in that case) OR the
4833 # plotter's render method was called and redraw_on_render is
4834 # enabled.
4835 if (plotter_render and self.redraw_on_render) or (not plotter_render and self._resize()):
4836 self._redraw()
4837
4838 @property
4839 def _geometry(self):
4840 r_w, r_h = self._renderer.GetSize()
4841 t_w = self._size[0] * r_w
4842 t_h = self._size[1] * r_h
4843 return (*self.position, t_w, t_h)
4844
4845 @_geometry.setter
4846 def _geometry(self, _):
4847 msg = f'Cannot set the geometry of {type(self).__class__}'
4848 raise AttributeError(msg)
4849
4850 @property
4851 def position(self): # numpydoc ignore=RT01
4852 """Chart position w.r.t the bottom left corner (in pixels)."""
4853 return self.GetPosition()
4854
4855 @position.setter
4856 def position(self, val):
4857 if len(val) != 2:
4858 msg = f'Invalid position {val}, must be length 2.'
4859 raise ValueError(msg)
4860 self.SetPosition(*val)
4861
4862 @property
4863 def title(self): # numpydoc ignore=RT01
4864 """Return or set the chart's title.
4865
4866 Examples
4867 --------
4868 Create a matplotlib chart with title 'My Chart'.
4869
4870
4871 .. pyvista-plot::
4872 :force_static:
4873
4874 >>> import pyvista as pv
4875 >>> import matplotlib.pyplot as plt
4876 >>> f, ax = plt.subplots()
4877 >>> _ = ax.plot([0, 1, 2], [2, 1, 3])
4878 >>> chart = pv.ChartMPL(f)
4879 >>> chart.title = 'My Chart'
4880 >>> chart.show()
4881
4882 """
4883 return self._fig._suptitle.get_text()
4884
4885 @title.setter
4886 def title(self, val) -> None:
4887 self._fig.suptitle(val)
4888
4889 @property
4890 def legend_visible(self): # numpydoc ignore=RT01
4891 """Return or set the visibility of the chart's legend.
4892
4893 Examples
4894 --------
4895 Create a matplotlib chart with custom labels and show the legend.
4896
4897 .. pyvista-plot::
4898 :force_static:
4899
4900 >>> import pyvista as pv
4901 >>> import matplotlib.pyplot as plt
4902 >>> f, ax = plt.subplots()
4903 >>> _ = ax.plot([0, 1, 2], [2, 1, 3], label='Line')
4904 >>> _ = ax.scatter([0, 1, 2], [3, 2, 1], label='Points')
4905 >>> chart = pv.ChartMPL(f)
4906 >>> chart.legend_visible = True
4907 >>> chart.show()
4908
4909 Hide the legend.
4910
4911 >>> chart.legend_visible = False
4912 >>> chart.show()
4913
4914 """
4915 legend = self._fig.axes[0].get_legend()
4916 return False if legend is None else legend.get_visible()
4917
4918 @legend_visible.setter
4919 def legend_visible(self, val) -> None:
4920 legend = self._fig.axes[0].get_legend()
4921 if legend is None:
4922 legend = self._fig.axes[0].legend()
4923 legend.set_visible(val)
4924
4925
4926 class Charts(_NoNewAttrMixin):
4927 """Collection of charts for a renderer.
4928
4929 Users should typically not directly create new instances of this
4930 class, but use the dedicated ``Plotter.add_chart`` method.
4931
4932 Parameters
4933 ----------
4934 renderer : pyvista.Renderer
4935 The renderer to which the charts should be added.
4936
4937 """
4938
4939 def __init__(self, renderer) -> None:
4940 """Create a new collection of charts for the given renderer."""
4941 self._charts: list[_Chart] = []
4942
4943 # Postpone creation of scene and actor objects until they are
4944 # needed.
4945 self._scene: _vtk.vtkContextScene | None = None
4946 self._actor: _vtk.vtkContextActor | None = None
4947
4948 # a weakref.proxy would be nice here, but that doesn't play
4949 # nicely with SetRenderer, so instead we'll use a weak reference
4950 # plus a property to call it
4951 self.__renderer = weakref.ref(renderer)
4952
4953 @property
4954 def _renderer(self):
4955 """Return the weakly dereferenced renderer, maybe None."""
4956 return self.__renderer()
4957
4958 def _setup_scene(self) -> None:
4959 """Set up a new context scene and actor for these charts."""
4960 self._scene = _vtk.vtkContextScene()
4961 self._actor = _vtk.vtkContextActor()
4962
4963 self._actor.SetScene(self._scene)
4964 self._renderer.AddActor(self._actor)
4965 self._scene.SetRenderer(self._renderer)
4966
4967 def deep_clean(self) -> None:
4968 """Remove all references to the chart objects and internal objects."""
4969 if self._scene is not None:
4970 charts = [*self._charts] # Make a copy, as this list will be modified by remove_chart
4971 for chart in charts:
4972 self.remove_chart(chart)
4973 if self._renderer is not None:
4974 self._renderer.RemoveActor(self._actor)
4975 self._scene = None
4976 self._actor = None
4977
4978 def add_chart(self, *charts) -> None:
4979 """Add charts to the collection.
4980
4981 Parameters
4982 ----------
4983 *charts : Chart2D | Chart3D
4984 One or more chart objects to be added to the collection.
4985
4986 See Also
4987 --------
4988 :ref:`chart_overlays_example`
4989
4990 """
4991 if self._scene is None:
4992 self._setup_scene()
4993 for chart in charts:
4994 self._charts.append(chart)
4995 if chart._background is not None:
4996 self._scene.AddItem(chart._background) # type: ignore[union-attr]
4997 self._scene.AddItem(chart) # type: ignore[union-attr]
4998 chart._interactive = False # Charts are not interactive by default
4999
5000 @_deprecate_positional_args(allowed=['interactive'])
5001 def set_interaction(self, interactive, toggle: bool = False): # noqa: FBT001, FBT002
5002 """Set or toggle interaction with charts for this renderer.
5003
5004 Interaction with other charts in this renderer is disabled when ``toggle``
5005 is ``False``.
5006
5007 Parameters
5008 ----------
5009 interactive : bool | Chart | int | list[Chart] | list[int]
5010 Following parameter values are accepted:
5011
5012 * A boolean to enable (``True``) or disable (``False``) interaction
5013 with all charts.
5014 * The chart or its index to enable interaction with. Interaction
5015 with multiple charts can be enabled by passing a list of charts
5016 or indices.
5017
5018 toggle : bool, default: False
5019 Instead of enabling interaction with the provided chart(s), interaction
5020 with the provided chart(s) is toggled. Only applicable when ``interactive``
5021 is not a boolean.
5022
5023 Returns
5024 -------
5025 list[Chart]
5026 The list of all interactive charts for this renderer.
5027
5028 """
5029 if isinstance(interactive, bool):
5030 # Disable toggle and convert to list of charts
5031 toggle = False
5032 interactive = self._charts if interactive else []
5033 if not isinstance(interactive, list):
5034 # Convert single chart parameter to list
5035 interactive = [interactive]
5036 # Convert to list of Charts
5037 charts = [
5038 self._charts[coi] if isinstance(coi, int) and 0 <= coi < len(self) else coi
5039 for coi in interactive
5040 ]
5041 interactive_charts = []
5042
5043 for chart in self._charts:
5044 # Determine whether to enable interaction with the current chart.
5045 if toggle:
5046 enable = not chart._interactive if chart in charts else chart._interactive
5047 else:
5048 enable = chart in charts
5049
5050 chart._interactive = enable
5051 if enable:
5052 interactive_charts.append(chart)
5053
5054 return interactive_charts
5055
5056 def remove_chart(self, chart_or_index):
5057 """Remove a chart from the collection.
5058
5059 Parameters
5060 ----------
5061 chart_or_index : int or Chart
5062 The index or the chart object to be removed from the collection.
5063
5064 Raises
5065 ------
5066 ValueError
5067 If the specified chart index is not present in the charts collection.
5068
5069 """
5070 chart: _Chart = (
5071 self._charts[chart_or_index] if isinstance(chart_or_index, int) else chart_or_index
5072 )
5073 if chart not in self._charts: # pragma: no cover
5074 msg = 'chart_index not present in charts collection.'
5075 raise ValueError(msg)
5076 self._charts.remove(chart)
5077 if self._scene is not None:
5078 self._scene.RemoveItem(chart) # type: ignore[call-overload]
5079 if chart._background is not None:
5080 self._scene.RemoveItem(chart._background) # type: ignore[union-attr]
5081
5082 def get_charts_by_pos(self, pos):
5083 """Retrieve visible charts indicated by the given mouse position.
5084
5085 Parameters
5086 ----------
5087 pos : sequence[float]
5088 Tuple containing the mouse position.
5089
5090 Returns
5091 -------
5092 list of Chart
5093 Visible charts indicated by the given mouse position.
5094
5095 """
5096 return [chart for chart in self._charts if chart.visible and chart._is_within(pos)]
5097
5098 def __getitem__(self, index) -> Chart:
5099 """Return a chart based on an index."""
5100 return self._charts[index]
5101
5102 def __len__(self):
5103 """Return number of charts."""
5104 return len(self._charts)
5105
5106 def __iter__(self):
5107 """Return an iterable of charts."""
5108 yield from self._charts
5109
5110 def __del__(self) -> None:
5111 """Clean up before being destroyed."""
5112 self.deep_clean()