_misc.py 24 KB

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