1from __future__ import annotations
2
3from contextlib import contextmanager
4from typing import (
5 TYPE_CHECKING,
6 Any,
7)
8
9from pandas.util._decorators import set_module
10
11from pandas.plotting._core import _get_plot_backend
12
13if TYPE_CHECKING:
14 from collections.abc import (
15 Generator,
16 Mapping,
17 )
18
19 from matplotlib.axes import Axes
20 from matplotlib.colors import Colormap
21 from matplotlib.figure import Figure
22 from matplotlib.table import Table
23 import numpy as np
24
25 from pandas import (
26 DataFrame,
27 Series,
28 )
29
30
31@set_module("pandas.plotting")
32def table(ax: Axes, data: DataFrame | Series, **kwargs) -> Table:
33 """
34 Helper function to convert DataFrame and Series to matplotlib.table.
35
36 This method provides an easy way to visualize tabular data within a Matplotlib
37 figure. It automatically extracts index and column labels from the DataFrame
38 or Series, unless explicitly specified. This function is particularly useful
39 when displaying summary tables alongside other plots or when creating static
40 reports. It utilizes the `matplotlib.pyplot.table` backend and allows
41 customization through various styling options available in Matplotlib.
42
43 Parameters
44 ----------
45 ax : Matplotlib axes object
46 The axes on which to draw the table.
47 data : DataFrame or Series
48 Data for table contents.
49 **kwargs
50 Keyword arguments to be passed to matplotlib.table.table.
51 If `rowLabels` or `colLabels` is not specified, data index or column
52 names will be used.
53
54 Returns
55 -------
56 matplotlib table object
57 The created table as a matplotlib Table object.
58
59 See Also
60 --------
61 DataFrame.plot : Make plots of DataFrame using matplotlib.
62 matplotlib.pyplot.table : Create a table from data in a Matplotlib plot.
63
64 Examples
65 --------
66
67 .. plot::
68 :context: close-figs
69
70 >>> import matplotlib.pyplot as plt
71 >>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
72 >>> fig, ax = plt.subplots()
73 >>> ax.axis("off")
74 (np.float64(0.0), np.float64(1.0), np.float64(0.0), np.float64(1.0))
75 >>> table = pd.plotting.table(
76 ... ax, df, loc="center", cellLoc="center", colWidths=[0.2, 0.2]
77 ... )
78 """
79 plot_backend = _get_plot_backend("matplotlib")
80 return plot_backend.table(
81 ax=ax, data=data, rowLabels=None, colLabels=None, **kwargs
82 )
83
84
85@set_module("pandas.plotting")
86def register() -> None:
87 """
88 Register pandas formatters and converters with matplotlib.
89
90 This function modifies the global ``matplotlib.units.registry``
91 dictionary. pandas adds custom converters for
92
93 * pd.Timestamp
94 * pd.Period
95 * np.datetime64
96 * datetime.datetime
97 * datetime.date
98 * datetime.time
99
100 See Also
101 --------
102 deregister_matplotlib_converters : Remove pandas formatters and converters.
103
104 Examples
105 --------
106 .. plot::
107 :context: close-figs
108
109 The following line is done automatically by pandas so
110 the plot can be rendered:
111
112 >>> pd.plotting.register_matplotlib_converters()
113
114 >>> df = pd.DataFrame(
115 ... {"ts": pd.period_range("2020", periods=2, freq="M"), "y": [1, 2]}
116 ... )
117 >>> plot = df.plot.line(x="ts", y="y")
118
119 Unsetting the register manually an error will be raised:
120
121 >>> pd.set_option(
122 ... "plotting.matplotlib.register_converters", False
123 ... ) # doctest: +SKIP
124 >>> df.plot.line(x="ts", y="y") # doctest: +SKIP
125 Traceback (most recent call last):
126 TypeError: float() argument must be a string or a real number, not 'Period'
127 """
128 plot_backend = _get_plot_backend("matplotlib")
129 plot_backend.register()
130
131
132@set_module("pandas.plotting")
133def deregister() -> None:
134 """
135 Remove pandas formatters and converters.
136
137 Removes the custom converters added by :func:`register`. This
138 attempts to set the state of the registry back to the state before
139 pandas registered its own units. Converters for pandas' own types like
140 Timestamp and Period are removed completely. Converters for types
141 pandas overwrites, like ``datetime.datetime``, are restored to their
142 original value.
143
144 See Also
145 --------
146 register_matplotlib_converters : Register pandas formatters and converters
147 with matplotlib.
148
149 Examples
150 --------
151 .. plot::
152 :context: close-figs
153
154 The following line is done automatically by pandas so
155 the plot can be rendered:
156
157 >>> pd.plotting.register_matplotlib_converters()
158
159 >>> df = pd.DataFrame(
160 ... {"ts": pd.period_range("2020", periods=2, freq="M"), "y": [1, 2]}
161 ... )
162 >>> plot = df.plot.line(x="ts", y="y")
163
164 Unsetting the register manually an error will be raised:
165
166 >>> pd.set_option(
167 ... "plotting.matplotlib.register_converters", False
168 ... ) # doctest: +SKIP
169 >>> df.plot.line(x="ts", y="y") # doctest: +SKIP
170 Traceback (most recent call last):
171 TypeError: float() argument must be a string or a real number, not 'Period'
172 """
173 plot_backend = _get_plot_backend("matplotlib")
174 plot_backend.deregister()
175
176
177@set_module("pandas.plotting")
178def scatter_matrix(
179 frame: DataFrame,
180 alpha: float = 0.5,
181 figsize: tuple[float, float] | None = None,
182 ax: Axes | None = None,
183 grid: bool = False,
184 diagonal: str = "hist",
185 marker: str = ".",
186 density_kwds: Mapping[str, Any] | None = None,
187 hist_kwds: Mapping[str, Any] | None = None,
188 range_padding: float = 0.05,
189 **kwargs,
190) -> np.ndarray:
191 """
192 Draw a matrix of scatter plots.
193
194 Each pair of numeric columns in the DataFrame is plotted against each other,
195 resulting in a matrix of scatter plots. The diagonal plots can display either
196 histograms or Kernel Density Estimation (KDE) plots for each variable.
197
198 Parameters
199 ----------
200 frame : DataFrame
201 The data to be plotted.
202 alpha : float, optional
203 Amount of transparency applied.
204 figsize : (float,float), optional
205 A tuple (width, height) in inches.
206 ax : Matplotlib axis object, optional
207 An existing Matplotlib axis object for the plots. If None, a new axis is
208 created.
209 grid : bool, optional
210 Setting this to True will show the grid.
211 diagonal : {'hist', 'kde'}
212 Pick between 'kde' and 'hist' for either Kernel Density Estimation or
213 Histogram plot in the diagonal.
214 marker : str, optional
215 Matplotlib marker type, default '.'.
216 density_kwds : keywords
217 Keyword arguments to be passed to kernel density estimate plot.
218 hist_kwds : keywords
219 Keyword arguments to be passed to hist function.
220 range_padding : float, default 0.05
221 Relative extension of axis range in x and y with respect to
222 (x_max - x_min) or (y_max - y_min).
223 **kwargs
224 Keyword arguments to be passed to scatter function.
225
226 Returns
227 -------
228 numpy.ndarray
229 A matrix of scatter plots.
230
231 See Also
232 --------
233 plotting.parallel_coordinates : Plots parallel coordinates for multivariate data.
234 plotting.andrews_curves : Generates Andrews curves for visualizing clusters of
235 multivariate data.
236 plotting.radviz : Creates a RadViz visualization.
237 plotting.bootstrap_plot : Visualizes uncertainty in data via bootstrap sampling.
238
239 Examples
240 --------
241
242 .. plot::
243 :context: close-figs
244
245 >>> df = pd.DataFrame(np.random.randn(1000, 4), columns=["A", "B", "C", "D"])
246 >>> pd.plotting.scatter_matrix(df, alpha=0.2)
247 array([[<Axes: xlabel='A', ylabel='A'>, <Axes: xlabel='B', ylabel='A'>,
248 <Axes: xlabel='C', ylabel='A'>, <Axes: xlabel='D', ylabel='A'>],
249 [<Axes: xlabel='A', ylabel='B'>, <Axes: xlabel='B', ylabel='B'>,
250 <Axes: xlabel='C', ylabel='B'>, <Axes: xlabel='D', ylabel='B'>],
251 [<Axes: xlabel='A', ylabel='C'>, <Axes: xlabel='B', ylabel='C'>,
252 <Axes: xlabel='C', ylabel='C'>, <Axes: xlabel='D', ylabel='C'>],
253 [<Axes: xlabel='A', ylabel='D'>, <Axes: xlabel='B', ylabel='D'>,
254 <Axes: xlabel='C', ylabel='D'>, <Axes: xlabel='D', ylabel='D'>]],
255 dtype=object)
256 """
257 plot_backend = _get_plot_backend("matplotlib")
258 return plot_backend.scatter_matrix(
259 frame=frame,
260 alpha=alpha,
261 figsize=figsize,
262 ax=ax,
263 grid=grid,
264 diagonal=diagonal,
265 marker=marker,
266 density_kwds=density_kwds,
267 hist_kwds=hist_kwds,
268 range_padding=range_padding,
269 **kwargs,
270 )
271
272
273@set_module("pandas.plotting")
274def radviz(
275 frame: DataFrame,
276 class_column: str,
277 ax: Axes | None = None,
278 color: list[str] | tuple[str, ...] | None = None,
279 colormap: Colormap | str | None = None,
280 **kwds,
281) -> Axes:
282 """
283 Plot a multidimensional dataset in 2D.
284
285 Each Series in the DataFrame is represented as an evenly distributed
286 slice on a circle. Each data point is rendered in the circle according to
287 the value on each Series. Highly correlated `Series` in the `DataFrame`
288 are placed closer on the unit circle.
289
290 RadViz allow to project an N-dimensional data set into a 2D space where the
291 influence of each dimension can be interpreted as a balance between the
292 influence of all dimensions.
293
294 More info available at the `original article
295 <https://doi.org/10.1145/331770.331775>`_
296 describing RadViz.
297
298 Parameters
299 ----------
300 frame : `DataFrame`
301 Object holding the data.
302 class_column : str
303 Column name containing the name of the data point category.
304 ax : :class:`matplotlib.axes.Axes`, optional
305 A plot instance to which to add the information.
306 color : list[str] or tuple[str], optional
307 Assign a color to each category. Example: ['blue', 'green'].
308 colormap : str or :class:`matplotlib.colors.Colormap`, default None
309 Colormap to select colors from. If string, load colormap with that
310 name from matplotlib.
311 **kwds
312 Options to pass to matplotlib scatter plotting method.
313
314 Returns
315 -------
316 :class:`matplotlib.axes.Axes`
317 The Axes object from Matplotlib.
318
319 See Also
320 --------
321 plotting.andrews_curves : Plot clustering visualization.
322
323 Examples
324 --------
325
326 .. plot::
327 :context: close-figs
328
329 >>> df = pd.DataFrame(
330 ... {
331 ... "SepalLength": [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6],
332 ... "SepalWidth": [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6],
333 ... "PetalLength": [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0],
334 ... "PetalWidth": [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2],
335 ... "Category": [
336 ... "virginica",
337 ... "virginica",
338 ... "setosa",
339 ... "virginica",
340 ... "virginica",
341 ... "versicolor",
342 ... "versicolor",
343 ... "setosa",
344 ... "virginica",
345 ... "setosa",
346 ... ],
347 ... }
348 ... )
349 >>> pd.plotting.radviz(df, "Category") # doctest: +SKIP
350 """
351 plot_backend = _get_plot_backend("matplotlib")
352 return plot_backend.radviz(
353 frame=frame,
354 class_column=class_column,
355 ax=ax,
356 color=color,
357 colormap=colormap,
358 **kwds,
359 )
360
361
362@set_module("pandas.plotting")
363def andrews_curves(
364 frame: DataFrame,
365 class_column: str,
366 ax: Axes | None = None,
367 samples: int = 200,
368 color: list[str] | tuple[str, ...] | None = None,
369 colormap: Colormap | str | None = None,
370 **kwargs,
371) -> Axes:
372 """
373 Generate a matplotlib plot for visualizing clusters of multivariate data.
374
375 Andrews curves have the functional form:
376
377 .. math::
378 f(t) = \\frac{x_1}{\\sqrt{2}} + x_2 \\sin(t) + x_3 \\cos(t) +
379 x_4 \\sin(2t) + x_5 \\cos(2t) + \\cdots
380
381 Where :math:`x` coefficients correspond to the values of each dimension
382 and :math:`t` is linearly spaced between :math:`-\\pi` and :math:`+\\pi`.
383 Each row of frame then corresponds to a single curve.
384
385 Parameters
386 ----------
387 frame : DataFrame
388 Data to be plotted, preferably normalized to (0.0, 1.0).
389 class_column : label
390 Name of the column containing class names.
391 ax : axes object, default None
392 Axes to use.
393 samples : int
394 Number of points to plot in each curve.
395 color : str, list[str] or tuple[str], optional
396 Colors to use for the different classes. Colors can be strings
397 or 3-element floating point RGB values.
398 colormap : str or matplotlib colormap object, default None
399 Colormap to select colors from. If a string, load colormap with that
400 name from matplotlib.
401 **kwargs
402 Options to pass to matplotlib plotting method.
403
404 Returns
405 -------
406 :class:`matplotlib.axes.Axes`
407 The matplotlib Axes object with the plot.
408
409 See Also
410 --------
411 plotting.parallel_coordinates : Plot parallel coordinates chart.
412 DataFrame.plot : Make plots of Series or DataFrame.
413
414 Examples
415 --------
416
417 .. plot::
418 :context: close-figs
419
420 >>> df = pd.read_csv(
421 ... "https://raw.githubusercontent.com/pandas-dev/"
422 ... "pandas/main/pandas/tests/io/data/csv/iris.csv"
423 ... ) # doctest: +SKIP
424 >>> pd.plotting.andrews_curves(df, "Name") # doctest: +SKIP
425 """
426 plot_backend = _get_plot_backend("matplotlib")
427 return plot_backend.andrews_curves(
428 frame=frame,
429 class_column=class_column,
430 ax=ax,
431 samples=samples,
432 color=color,
433 colormap=colormap,
434 **kwargs,
435 )
436
437
438@set_module("pandas.plotting")
439def bootstrap_plot(
440 series: Series,
441 fig: Figure | None = None,
442 size: int = 50,
443 samples: int = 500,
444 **kwds,
445) -> Figure:
446 """
447 Bootstrap plot on mean, median and mid-range statistics.
448
449 The bootstrap plot is used to estimate the uncertainty of a statistic
450 by relying on random sampling with replacement [1]_. This function will
451 generate bootstrapping plots for mean, median and mid-range statistics
452 for the given number of samples of the given size.
453
454 .. [1] "Bootstrapping (statistics)" in \
455 https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
456
457 Parameters
458 ----------
459 series : pandas.Series
460 Series from where to get the samplings for the bootstrapping.
461 fig : matplotlib.figure.Figure, default None
462 If given, it will use the `fig` reference for plotting instead of
463 creating a new one with default parameters.
464 size : int, default 50
465 Number of data points to consider during each sampling. It must be
466 less than or equal to the length of the `series`.
467 samples : int, default 500
468 Number of times the bootstrap procedure is performed.
469 **kwds
470 Options to pass to matplotlib plotting method.
471
472 Returns
473 -------
474 matplotlib.figure.Figure
475 Matplotlib figure.
476
477 See Also
478 --------
479 DataFrame.plot : Basic plotting for DataFrame objects.
480 Series.plot : Basic plotting for Series objects.
481
482 Examples
483 --------
484 This example draws a basic bootstrap plot for a Series.
485
486 .. plot::
487 :context: close-figs
488
489 >>> s = pd.Series(np.random.uniform(size=100))
490 >>> pd.plotting.bootstrap_plot(s) # doctest: +SKIP
491 <Figure size 640x480 with 6 Axes>
492 """
493 plot_backend = _get_plot_backend("matplotlib")
494 return plot_backend.bootstrap_plot(
495 series=series, fig=fig, size=size, samples=samples, **kwds
496 )
497
498
499@set_module("pandas.plotting")
500def parallel_coordinates(
501 frame: DataFrame,
502 class_column: str,
503 cols: list[str] | None = None,
504 ax: Axes | None = None,
505 color: list[str] | tuple[str, ...] | None = None,
506 use_columns: bool = False,
507 xticks: list | tuple | None = None,
508 colormap: Colormap | str | None = None,
509 axvlines: bool = True,
510 axvlines_kwds: Mapping[str, Any] | None = None,
511 sort_labels: bool = False,
512 **kwargs,
513) -> Axes:
514 """
515 Parallel coordinates plotting.
516
517 Parameters
518 ----------
519 frame : DataFrame
520 The DataFrame to be plotted.
521 class_column : str
522 Column name containing class names.
523 cols : list, optional
524 A list of column names to use.
525 ax : matplotlib.axis, optional
526 Matplotlib axis object.
527 color : list or tuple, optional
528 Colors to use for the different classes.
529 use_columns : bool, optional
530 If true, columns will be used as xticks.
531 xticks : list or tuple, optional
532 A list of values to use for xticks.
533 colormap : str or matplotlib colormap, default None
534 Colormap to use for line colors.
535 axvlines : bool, optional
536 If true, vertical lines will be added at each xtick.
537 axvlines_kwds : keywords, optional
538 Options to be passed to axvline method for vertical lines.
539 sort_labels : bool, default False
540 Sort class_column labels, useful when assigning colors.
541 **kwargs
542 Options to pass to matplotlib plotting method.
543
544 Returns
545 -------
546 matplotlib.axes.Axes
547 The matplotlib axes containing the parallel coordinates plot.
548
549 See Also
550 --------
551 plotting.andrews_curves : Generate a matplotlib plot for visualizing clusters
552 of multivariate data.
553 plotting.radviz : Plot a multidimensional dataset in 2D.
554
555 Examples
556 --------
557
558 .. plot::
559 :context: close-figs
560
561 >>> df = pd.read_csv(
562 ... "https://raw.githubusercontent.com/pandas-dev/"
563 ... "pandas/main/pandas/tests/io/data/csv/iris.csv"
564 ... ) # doctest: +SKIP
565 >>> pd.plotting.parallel_coordinates(
566 ... df, "Name", color=("#556270", "#4ECDC4", "#C7F464")
567 ... ) # doctest: +SKIP
568 """
569 plot_backend = _get_plot_backend("matplotlib")
570 return plot_backend.parallel_coordinates(
571 frame=frame,
572 class_column=class_column,
573 cols=cols,
574 ax=ax,
575 color=color,
576 use_columns=use_columns,
577 xticks=xticks,
578 colormap=colormap,
579 axvlines=axvlines,
580 axvlines_kwds=axvlines_kwds,
581 sort_labels=sort_labels,
582 **kwargs,
583 )
584
585
586@set_module("pandas.plotting")
587def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Axes:
588 """
589 Lag plot for time series.
590
591 A lag plot is a scatter plot of a time series against a lag of itself. It helps
592 in visualizing the temporal dependence between observations by plotting the values
593 at time `t` on the x-axis and the values at time `t + lag` on the y-axis.
594
595 Parameters
596 ----------
597 series : Series
598 The time series to visualize.
599 lag : int, default 1
600 Lag length of the scatter plot.
601 ax : Matplotlib axis object, optional
602 The matplotlib axis object to use.
603 **kwds
604 Matplotlib scatter method keyword arguments.
605
606 Returns
607 -------
608 matplotlib.axes.Axes
609 The matplotlib Axes object containing the lag plot.
610
611 See Also
612 --------
613 plotting.autocorrelation_plot : Autocorrelation plot for time series.
614 matplotlib.pyplot.scatter : A scatter plot of y vs. x with varying marker size
615 and/or color in Matplotlib.
616
617 Examples
618 --------
619 Lag plots are most commonly used to look for patterns in time series data.
620
621 Given the following time series
622
623 .. plot::
624 :context: close-figs
625
626 >>> np.random.seed(5)
627 >>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50))
628 >>> s = pd.Series(x)
629 >>> s.plot() # doctest: +SKIP
630
631 A lag plot with ``lag=1`` returns
632
633 .. plot::
634 :context: close-figs
635
636 >>> _ = pd.plotting.lag_plot(s, lag=1)
637 """
638 plot_backend = _get_plot_backend("matplotlib")
639 return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds)
640
641
642@set_module("pandas.plotting")
643def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Axes:
644 """
645 Autocorrelation plot for time series.
646
647 This method generates an autocorrelation plot for a given time series,
648 which helps to identify any periodic structure or correlation within the
649 data across various lags. It shows the correlation of a time series with a
650 delayed copy of itself as a function of delay. Autocorrelation plots are useful for
651 checking randomness in a data set. If the data are random, the autocorrelations
652 should be near zero for any and all time-lag separations. If the data are not
653 random, then one or more of the autocorrelations will be significantly
654 non-zero.
655
656 Parameters
657 ----------
658 series : Series
659 The time series to visualize.
660 ax : Matplotlib axis object, optional
661 The matplotlib axis object to use.
662 **kwargs
663 Options to pass to matplotlib plotting method.
664
665 Returns
666 -------
667 matplotlib.axes.Axes
668 The matplotlib axes containing the autocorrelation plot.
669
670 See Also
671 --------
672 Series.autocorr : Compute the lag-N autocorrelation for a Series.
673 plotting.lag_plot : Lag plot for time series.
674
675 Examples
676 --------
677 The horizontal lines in the plot correspond to 95% and 99% confidence bands.
678
679 The dashed line is 99% confidence band.
680
681 .. plot::
682 :context: close-figs
683
684 >>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
685 >>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
686 >>> pd.plotting.autocorrelation_plot(s) # doctest: +SKIP
687 """
688 plot_backend = _get_plot_backend("matplotlib")
689 return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs)
690
691
692class _Options(dict):
693 """
694 Stores pandas plotting options.
695
696 Allows for parameter aliasing so you can just use parameter names that are
697 the same as the plot function parameters, but is stored in a canonical
698 format that makes it easy to breakdown into groups later.
699
700 See Also
701 --------
702 plotting.register_matplotlib_converters : Register pandas formatters and
703 converters with matplotlib.
704 plotting.bootstrap_plot : Bootstrap plot on mean, median and mid-range statistics.
705 plotting.autocorrelation_plot : Autocorrelation plot for time series.
706 plotting.lag_plot : Lag plot for time series.
707
708 Examples
709 --------
710
711 .. plot::
712 :context: close-figs
713
714 >>> np.random.seed(42)
715 >>> df = pd.DataFrame(
716 ... {"A": np.random.randn(10), "B": np.random.randn(10)},
717 ... index=pd.date_range("1/1/2000", freq="4MS", periods=10),
718 ... )
719 >>> with pd.plotting.plot_params.use("x_compat", True):
720 ... _ = df["A"].plot(color="r")
721 ... _ = df["B"].plot(color="g")
722 """
723
724 # alias so the names are same as plotting method parameter names
725 _ALIASES = {"x_compat": "xaxis.compat"}
726 _DEFAULT_KEYS = ["xaxis.compat"]
727
728 def __init__(self) -> None:
729 super().__setitem__("xaxis.compat", False)
730
731 def __getitem__(self, key):
732 key = self._get_canonical_key(key)
733 if key not in self:
734 raise ValueError(f"{key} is not a valid pandas plotting option")
735 return super().__getitem__(key)
736
737 def __setitem__(self, key, value) -> None:
738 key = self._get_canonical_key(key)
739 super().__setitem__(key, value)
740
741 def __delitem__(self, key) -> None:
742 key = self._get_canonical_key(key)
743 if key in self._DEFAULT_KEYS:
744 raise ValueError(f"Cannot remove default parameter {key}")
745 super().__delitem__(key)
746
747 def __contains__(self, key) -> bool:
748 key = self._get_canonical_key(key)
749 return super().__contains__(key)
750
751 def reset(self) -> None:
752 """
753 Reset the option store to its initial state
754
755 Returns
756 -------
757 None
758 """
759 # error: Cannot access "__init__" directly
760 self.__init__() # type: ignore[misc]
761
762 def _get_canonical_key(self, key: str) -> str:
763 return self._ALIASES.get(key, key)
764
765 @contextmanager
766 def use(self, key, value) -> Generator[_Options]:
767 """
768 Temporarily set a parameter value using the with statement.
769 Aliasing allowed.
770 """
771 old_value = self[key]
772 try:
773 self[key] = value
774 yield self
775 finally:
776 self[key] = old_value
777
778
779plot_params = _Options()
780plot_params.__module__ = "pandas.plotting"