Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pandas/plotting/_misc.py: 47%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

87 statements  

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 >>> data = np.random.default_rng(42).standard_normal((1000, 4)) 

246 >>> df = pd.DataFrame(data, columns=["A", "B", "C", "D"]) 

247 >>> pd.plotting.scatter_matrix(df, alpha=0.2) 

248 array([[<Axes: xlabel='A', ylabel='A'>, <Axes: xlabel='B', ylabel='A'>, 

249 <Axes: xlabel='C', ylabel='A'>, <Axes: xlabel='D', ylabel='A'>], 

250 [<Axes: xlabel='A', ylabel='B'>, <Axes: xlabel='B', ylabel='B'>, 

251 <Axes: xlabel='C', ylabel='B'>, <Axes: xlabel='D', ylabel='B'>], 

252 [<Axes: xlabel='A', ylabel='C'>, <Axes: xlabel='B', ylabel='C'>, 

253 <Axes: xlabel='C', ylabel='C'>, <Axes: xlabel='D', ylabel='C'>], 

254 [<Axes: xlabel='A', ylabel='D'>, <Axes: xlabel='B', ylabel='D'>, 

255 <Axes: xlabel='C', ylabel='D'>, <Axes: xlabel='D', ylabel='D'>]], 

256 dtype=object) 

257 """ 

258 plot_backend = _get_plot_backend("matplotlib") 

259 return plot_backend.scatter_matrix( 

260 frame=frame, 

261 alpha=alpha, 

262 figsize=figsize, 

263 ax=ax, 

264 grid=grid, 

265 diagonal=diagonal, 

266 marker=marker, 

267 density_kwds=density_kwds, 

268 hist_kwds=hist_kwds, 

269 range_padding=range_padding, 

270 **kwargs, 

271 ) 

272 

273 

274@set_module("pandas.plotting") 

275def radviz( 

276 frame: DataFrame, 

277 class_column: str, 

278 ax: Axes | None = None, 

279 color: list[str] | tuple[str, ...] | None = None, 

280 colormap: Colormap | str | None = None, 

281 **kwds, 

282) -> Axes: 

283 """ 

284 Plot a multidimensional dataset in 2D. 

285 

286 Each Series in the DataFrame is represented as an evenly distributed 

287 slice on a circle. Each data point is rendered in the circle according to 

288 the value on each Series. Highly correlated `Series` in the `DataFrame` 

289 are placed closer on the unit circle. 

290 

291 RadViz allows you to project an N-dimensional data set into a 2D space 

292 where the influence of each dimension can be interpreted as a balance 

293 between the influence of all dimensions. 

294 

295 More info available at the `original article 

296 <https://doi.org/10.1145/331770.331775>`_ 

297 describing RadViz. 

298 

299 Parameters 

300 ---------- 

301 frame : `DataFrame` 

302 Object holding the data. 

303 class_column : str 

304 Column name containing the name of the data point category. 

305 ax : :class:`matplotlib.axes.Axes`, optional 

306 A plot instance to which to add the information. 

307 color : list[str] or tuple[str], optional 

308 Assign a color to each category. Example: ['blue', 'green']. 

309 colormap : str or :class:`matplotlib.colors.Colormap`, default None 

310 Colormap to select colors from. If string, load colormap with that 

311 name from matplotlib. 

312 **kwds 

313 Options to pass to matplotlib scatter plotting method. 

314 

315 Returns 

316 ------- 

317 :class:`matplotlib.axes.Axes` 

318 The Axes object from Matplotlib. 

319 

320 See Also 

321 -------- 

322 plotting.andrews_curves : Plot clustering visualization. 

323 

324 Examples 

325 -------- 

326 

327 .. plot:: 

328 :context: close-figs 

329 

330 >>> df = pd.DataFrame( 

331 ... { 

332 ... "SepalLength": [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6], 

333 ... "SepalWidth": [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6], 

334 ... "PetalLength": [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0], 

335 ... "PetalWidth": [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2], 

336 ... "Category": [ 

337 ... "virginica", 

338 ... "virginica", 

339 ... "setosa", 

340 ... "virginica", 

341 ... "virginica", 

342 ... "versicolor", 

343 ... "versicolor", 

344 ... "setosa", 

345 ... "virginica", 

346 ... "setosa", 

347 ... ], 

348 ... } 

349 ... ) 

350 >>> pd.plotting.radviz(df, "Category") # doctest: +SKIP 

351 """ 

352 plot_backend = _get_plot_backend("matplotlib") 

353 return plot_backend.radviz( 

354 frame=frame, 

355 class_column=class_column, 

356 ax=ax, 

357 color=color, 

358 colormap=colormap, 

359 **kwds, 

360 ) 

361 

362 

363@set_module("pandas.plotting") 

364def andrews_curves( 

365 frame: DataFrame, 

366 class_column: str, 

367 ax: Axes | None = None, 

368 samples: int = 200, 

369 color: list[str] | tuple[str, ...] | None = None, 

370 colormap: Colormap | str | None = None, 

371 **kwargs, 

372) -> Axes: 

373 """ 

374 Generate a matplotlib plot for visualizing clusters of multivariate data. 

375 

376 Andrews curves have the functional form: 

377 

378 .. math:: 

379 f(t) = \\frac{x_1}{\\sqrt{2}} + x_2 \\sin(t) + x_3 \\cos(t) + 

380 x_4 \\sin(2t) + x_5 \\cos(2t) + \\cdots 

381 

382 Where :math:`x` coefficients correspond to the values of each dimension 

383 and :math:`t` is linearly spaced between :math:`-\\pi` and :math:`+\\pi`. 

384 Each row of frame then corresponds to a single curve. 

385 

386 Parameters 

387 ---------- 

388 frame : DataFrame 

389 Data to be plotted, preferably normalized to (0.0, 1.0). 

390 class_column : label 

391 Name of the column containing class names. 

392 ax : axes object, default None 

393 Axes to use. 

394 samples : int 

395 Number of points to plot in each curve. 

396 color : str, list[str] or tuple[str], optional 

397 Colors to use for the different classes. Colors can be strings 

398 or 3-element floating point RGB values. 

399 colormap : str or matplotlib colormap object, default None 

400 Colormap to select colors from. If a string, load colormap with that 

401 name from matplotlib. 

402 **kwargs 

403 Options to pass to matplotlib plotting method. 

404 

405 Returns 

406 ------- 

407 :class:`matplotlib.axes.Axes` 

408 The matplotlib Axes object with the plot. 

409 

410 See Also 

411 -------- 

412 plotting.parallel_coordinates : Plot parallel coordinates chart. 

413 DataFrame.plot : Make plots of Series or DataFrame. 

414 

415 Examples 

416 -------- 

417 

418 .. plot:: 

419 :context: close-figs 

420 

421 >>> df = pd.DataFrame( 

422 ... { 

423 ... "SepalLength": [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6], 

424 ... "SepalWidth": [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6], 

425 ... "PetalLength": [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0], 

426 ... "PetalWidth": [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2], 

427 ... "Name": [ 

428 ... "virginica", 

429 ... "virginica", 

430 ... "setosa", 

431 ... "virginica", 

432 ... "virginica", 

433 ... "versicolor", 

434 ... "versicolor", 

435 ... "setosa", 

436 ... "virginica", 

437 ... "setosa", 

438 ... ], 

439 ... } 

440 ... ) 

441 >>> pd.plotting.andrews_curves(df, "Name") # doctest: +SKIP 

442 """ 

443 plot_backend = _get_plot_backend("matplotlib") 

444 return plot_backend.andrews_curves( 

445 frame=frame, 

446 class_column=class_column, 

447 ax=ax, 

448 samples=samples, 

449 color=color, 

450 colormap=colormap, 

451 **kwargs, 

452 ) 

453 

454 

455@set_module("pandas.plotting") 

456def bootstrap_plot( 

457 series: Series, 

458 fig: Figure | None = None, 

459 size: int = 50, 

460 samples: int = 500, 

461 **kwds, 

462) -> Figure: 

463 """ 

464 Bootstrap plot on mean, median and mid-range statistics. 

465 

466 The bootstrap plot is used to estimate the uncertainty of a statistic 

467 by relying on random sampling with replacement [1]_. This function will 

468 generate bootstrapping plots for mean, median and mid-range statistics 

469 for the given number of samples of the given size. 

470 

471 .. [1] "Bootstrapping (statistics)" in \ 

472 https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29 

473 

474 Parameters 

475 ---------- 

476 series : pandas.Series 

477 Series from where to get the samplings for the bootstrapping. 

478 fig : matplotlib.figure.Figure, default None 

479 If given, it will use the `fig` reference for plotting instead of 

480 creating a new one with default parameters. 

481 size : int, default 50 

482 Number of data points to consider during each sampling. It must be 

483 less than or equal to the length of the `series`. 

484 samples : int, default 500 

485 Number of times the bootstrap procedure is performed. 

486 **kwds 

487 Options to pass to matplotlib plotting method. 

488 

489 Returns 

490 ------- 

491 matplotlib.figure.Figure 

492 Matplotlib figure. 

493 

494 See Also 

495 -------- 

496 DataFrame.plot : Basic plotting for DataFrame objects. 

497 Series.plot : Basic plotting for Series objects. 

498 

499 Examples 

500 -------- 

501 This example draws a basic bootstrap plot for a Series. 

502 

503 .. plot:: 

504 :context: close-figs 

505 

506 >>> rng = np.random.default_rng(42) 

507 >>> s = pd.Series(rng.uniform(size=100)) 

508 >>> pd.plotting.bootstrap_plot(s) # doctest: +SKIP 

509 <Figure size 640x480 with 6 Axes> 

510 """ 

511 plot_backend = _get_plot_backend("matplotlib") 

512 return plot_backend.bootstrap_plot( 

513 series=series, fig=fig, size=size, samples=samples, **kwds 

514 ) 

515 

516 

517@set_module("pandas.plotting") 

518def parallel_coordinates( 

519 frame: DataFrame, 

520 class_column: str, 

521 cols: list[str] | None = None, 

522 ax: Axes | None = None, 

523 color: list[str] | tuple[str, ...] | None = None, 

524 use_columns: bool = False, 

525 xticks: list[float] | tuple[float, ...] | None = None, 

526 colormap: Colormap | str | None = None, 

527 axvlines: bool = True, 

528 axvlines_kwds: Mapping[str, Any] | None = None, 

529 sort_labels: bool = False, 

530 **kwargs, 

531) -> Axes: 

532 """ 

533 Parallel coordinates plotting. 

534 

535 This visualization technique represents each observation as a polyline 

536 connecting values across vertical axes, one for each feature. Lines are 

537 colored by class membership, making it useful for identifying clusters 

538 and separability in multivariate data. 

539 

540 Parameters 

541 ---------- 

542 frame : DataFrame 

543 The DataFrame to be plotted. 

544 class_column : str 

545 Column name containing class names. 

546 cols : list, optional 

547 A list of column names to use. 

548 ax : matplotlib.axis, optional 

549 Matplotlib axis object. 

550 color : list or tuple, optional 

551 Colors to use for the different classes. 

552 use_columns : bool, optional 

553 If true, columns will be used as xticks. 

554 xticks : list or tuple, optional 

555 A list of values to use for xticks. 

556 colormap : str or matplotlib colormap, default None 

557 Colormap to use for line colors. 

558 axvlines : bool, optional 

559 If true, vertical lines will be added at each xtick. 

560 axvlines_kwds : keywords, optional 

561 Options to be passed to axvline method for vertical lines. 

562 sort_labels : bool, default False 

563 Sort class_column labels, useful when assigning colors. 

564 **kwargs 

565 Options to pass to matplotlib plotting method. 

566 

567 Returns 

568 ------- 

569 matplotlib.axes.Axes 

570 The matplotlib axes containing the parallel coordinates plot. 

571 

572 See Also 

573 -------- 

574 plotting.andrews_curves : Generate a matplotlib plot for visualizing clusters 

575 of multivariate data. 

576 plotting.radviz : Plot a multidimensional dataset in 2D. 

577 

578 Examples 

579 -------- 

580 

581 .. plot:: 

582 :context: close-figs 

583 

584 >>> df = pd.DataFrame( 

585 ... { 

586 ... "SepalLength": [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6], 

587 ... "SepalWidth": [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6], 

588 ... "PetalLength": [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0], 

589 ... "PetalWidth": [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2], 

590 ... "Name": [ 

591 ... "virginica", 

592 ... "virginica", 

593 ... "setosa", 

594 ... "virginica", 

595 ... "virginica", 

596 ... "versicolor", 

597 ... "versicolor", 

598 ... "setosa", 

599 ... "virginica", 

600 ... "setosa", 

601 ... ], 

602 ... } 

603 ... ) 

604 >>> pd.plotting.parallel_coordinates( 

605 ... df, "Name", color=("#556270", "#4ECDC4", "#C7F464") 

606 ... ) # doctest: +SKIP 

607 """ 

608 plot_backend = _get_plot_backend("matplotlib") 

609 return plot_backend.parallel_coordinates( 

610 frame=frame, 

611 class_column=class_column, 

612 cols=cols, 

613 ax=ax, 

614 color=color, 

615 use_columns=use_columns, 

616 xticks=xticks, 

617 colormap=colormap, 

618 axvlines=axvlines, 

619 axvlines_kwds=axvlines_kwds, 

620 sort_labels=sort_labels, 

621 **kwargs, 

622 ) 

623 

624 

625@set_module("pandas.plotting") 

626def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Axes: 

627 """ 

628 Lag plot for time series. 

629 

630 A lag plot is a scatter plot of a time series against a lag of itself. It helps 

631 in visualizing the temporal dependence between observations by plotting the values 

632 at time `t` on the x-axis and the values at time `t + lag` on the y-axis. 

633 

634 Parameters 

635 ---------- 

636 series : Series 

637 The time series to visualize. 

638 lag : int, default 1 

639 Lag length of the scatter plot. 

640 ax : Matplotlib axis object, optional 

641 The matplotlib axis object to use. 

642 **kwds 

643 Matplotlib scatter method keyword arguments. 

644 

645 Returns 

646 ------- 

647 matplotlib.axes.Axes 

648 The matplotlib Axes object containing the lag plot. 

649 

650 See Also 

651 -------- 

652 plotting.autocorrelation_plot : Autocorrelation plot for time series. 

653 matplotlib.pyplot.scatter : A scatter plot of y vs. x with varying marker size 

654 and/or color in Matplotlib. 

655 

656 Examples 

657 -------- 

658 Lag plots are most commonly used to look for patterns in time series data. 

659 

660 Given the following time series 

661 

662 .. plot:: 

663 :context: close-figs 

664 

665 >>> rng = np.random.default_rng(42) 

666 >>> x = np.cumsum(rng.normal(loc=1, scale=5, size=50)) 

667 >>> s = pd.Series(x) 

668 >>> s.plot() # doctest: +SKIP 

669 

670 A lag plot with ``lag=1`` returns 

671 

672 .. plot:: 

673 :context: close-figs 

674 

675 >>> _ = pd.plotting.lag_plot(s, lag=1) 

676 """ 

677 plot_backend = _get_plot_backend("matplotlib") 

678 return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds) 

679 

680 

681@set_module("pandas.plotting") 

682def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Axes: 

683 """ 

684 Autocorrelation plot for time series. 

685 

686 This method generates an autocorrelation plot for a given time series, 

687 which helps to identify any periodic structure or correlation within the 

688 data across various lags. It shows the correlation of a time series with a 

689 delayed copy of itself as a function of delay. Autocorrelation plots are useful for 

690 checking randomness in a data set. If the data are random, the autocorrelations 

691 should be near zero for any and all time-lag separations. If the data are not 

692 random, then one or more of the autocorrelations will be significantly 

693 non-zero. 

694 

695 Parameters 

696 ---------- 

697 series : Series 

698 The time series to visualize. 

699 ax : Matplotlib axis object, optional 

700 The matplotlib axis object to use. 

701 **kwargs 

702 Options to pass to matplotlib plotting method. 

703 

704 Returns 

705 ------- 

706 matplotlib.axes.Axes 

707 The matplotlib axes containing the autocorrelation plot. 

708 

709 See Also 

710 -------- 

711 Series.autocorr : Compute the lag-N autocorrelation for a Series. 

712 plotting.lag_plot : Lag plot for time series. 

713 

714 Examples 

715 -------- 

716 The horizontal lines in the plot correspond to 95% and 99% confidence bands. 

717 

718 The dashed line is 99% confidence band. 

719 

720 .. plot:: 

721 :context: close-figs 

722 

723 >>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000) 

724 >>> rng = np.random.default_rng(42) 

725 >>> s = pd.Series(0.7 * rng.random(1000) + 0.3 * np.sin(spacing)) 

726 >>> pd.plotting.autocorrelation_plot(s) # doctest: +SKIP 

727 """ 

728 plot_backend = _get_plot_backend("matplotlib") 

729 return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs) 

730 

731 

732class _Options(dict[str, Any]): 

733 """ 

734 Stores pandas plotting options. 

735 

736 Allows for parameter aliasing so you can just use parameter names that are 

737 the same as the plot function parameters, but is stored in a canonical 

738 format that makes it easy to breakdown into groups later. 

739 

740 See Also 

741 -------- 

742 plotting.register_matplotlib_converters : Register pandas formatters and 

743 converters with matplotlib. 

744 plotting.bootstrap_plot : Bootstrap plot on mean, median and mid-range statistics. 

745 plotting.autocorrelation_plot : Autocorrelation plot for time series. 

746 plotting.lag_plot : Lag plot for time series. 

747 

748 Examples 

749 -------- 

750 

751 .. plot:: 

752 :context: close-figs 

753 

754 >>> rng = np.random.default_rng(42) 

755 >>> df = pd.DataFrame( 

756 ... {"A": rng.standard_normal(10), "B": rng.standard_normal(10)}, 

757 ... index=pd.date_range("1/1/2000", freq="4MS", periods=10), 

758 ... ) 

759 >>> with pd.plotting.plot_params.use("x_compat", True): 

760 ... _ = df["A"].plot(color="r") 

761 ... _ = df["B"].plot(color="g") 

762 """ 

763 

764 # alias so the names are same as plotting method parameter names 

765 _ALIASES = {"x_compat": "xaxis.compat"} 

766 _DEFAULT_KEYS = ["xaxis.compat"] 

767 

768 def __init__(self) -> None: 

769 super().__setitem__("xaxis.compat", False) 

770 

771 def __getitem__(self, key): 

772 key = self._get_canonical_key(key) 

773 if key not in self: 

774 raise ValueError(f"{key} is not a valid pandas plotting option") 

775 return super().__getitem__(key) 

776 

777 def __setitem__(self, key, value) -> None: 

778 key = self._get_canonical_key(key) 

779 super().__setitem__(key, value) 

780 

781 def __delitem__(self, key) -> None: 

782 key = self._get_canonical_key(key) 

783 if key in self._DEFAULT_KEYS: 

784 raise ValueError(f"Cannot remove default parameter {key}") 

785 super().__delitem__(key) 

786 

787 def __contains__(self, key) -> bool: 

788 key = self._get_canonical_key(key) 

789 return super().__contains__(key) 

790 

791 def reset(self) -> None: 

792 """ 

793 Reset the option store to its initial state 

794 

795 Returns 

796 ------- 

797 None 

798 """ 

799 # error: Cannot access "__init__" directly 

800 self.__init__() # type: ignore[misc] 

801 

802 def _get_canonical_key(self, key: str) -> str: 

803 return self._ALIASES.get(key, key) 

804 

805 @contextmanager 

806 def use(self, key, value) -> Generator[_Options]: 

807 """ 

808 Temporarily set a parameter value using the with statement. 

809 Aliasing allowed. 

810 """ 

811 old_value = self[key] 

812 try: 

813 self[key] = value 

814 yield self 

815 finally: 

816 self[key] = old_value 

817 

818 

819plot_params = _Options() 

820plot_params.__module__ = "pandas.plotting"