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

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

193 statements  

1from __future__ import annotations 

2 

3import importlib 

4from typing import ( 

5 TYPE_CHECKING, 

6 Literal, 

7) 

8 

9from pandas._config.config import _global_config as config 

10 

11from pandas.util._decorators import set_module 

12 

13from pandas.core.dtypes.common import ( 

14 is_integer, 

15 is_list_like, 

16) 

17from pandas.core.dtypes.generic import ( 

18 ABCDataFrame, 

19 ABCSeries, 

20) 

21 

22from pandas.core.base import PandasObject 

23 

24if TYPE_CHECKING: 

25 from collections.abc import ( 

26 Callable, 

27 Hashable, 

28 Sequence, 

29 ) 

30 import types 

31 

32 from matplotlib.axes import Axes 

33 import numpy as np 

34 

35 from pandas._typing import IndexLabel 

36 

37 from pandas import ( 

38 DataFrame, 

39 Index, 

40 Series, 

41 ) 

42 from pandas.core.groupby.generic import DataFrameGroupBy 

43 

44 

45def holds_integer(column: Index) -> bool: 

46 return column.dtype.kind in "iu" 

47 

48 

49@set_module("pandas.plotting") 

50def hist_series( 

51 self: Series, 

52 by=None, 

53 ax=None, 

54 grid: bool = True, 

55 xlabelsize: int | None = None, 

56 xrot: float | None = None, 

57 ylabelsize: int | None = None, 

58 yrot: float | None = None, 

59 figsize: tuple[int, int] | None = None, 

60 bins: int | Sequence[int] = 10, 

61 backend: str | None = None, 

62 legend: bool = False, 

63 **kwargs, 

64): 

65 """ 

66 Draw histogram of the input series using matplotlib. 

67 

68 The histogram is computed over the fixed or variable width bins, 

69 and drawn using the matplotlib library. This is useful for 

70 visualizing the distribution of the data. 

71 

72 Parameters 

73 ---------- 

74 by : object, optional 

75 If passed, then used to form histograms for separate groups. 

76 ax : matplotlib axis object 

77 If not passed, uses gca(). 

78 grid : bool, default True 

79 Whether to show axis grid lines. 

80 xlabelsize : int, default None 

81 If specified changes the x-axis label size. 

82 xrot : float, default None 

83 Rotation of x axis labels. 

84 ylabelsize : int, default None 

85 If specified changes the y-axis label size. 

86 yrot : float, default None 

87 Rotation of y axis labels. 

88 figsize : tuple, default None 

89 Figure size in inches by default. 

90 bins : int or sequence, default 10 

91 Number of histogram bins to be used. If an integer is given, bins + 1 

92 bin edges are calculated and returned. If bins is a sequence, gives 

93 bin edges, including left edge of first bin and right edge of last 

94 bin. In this case, bins is returned unmodified. 

95 backend : str, default None 

96 Backend to use instead of the backend specified in the option 

97 ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to 

98 specify the ``plotting.backend`` for the whole session, set 

99 ``pd.options.plotting.backend``. 

100 legend : bool, default False 

101 Whether to show the legend. 

102 

103 **kwargs 

104 To be passed to the actual plotting function. 

105 

106 Returns 

107 ------- 

108 matplotlib.axes.Axes 

109 A histogram plot. 

110 

111 See Also 

112 -------- 

113 matplotlib.axes.Axes.hist : Plot a histogram using matplotlib. 

114 

115 Examples 

116 -------- 

117 For Series: 

118 

119 .. plot:: 

120 :context: close-figs 

121 

122 >>> lst = ["a", "a", "a", "b", "b", "b"] 

123 >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst) 

124 >>> hist = ser.hist() 

125 

126 For Groupby: 

127 

128 .. plot:: 

129 :context: close-figs 

130 

131 >>> lst = ["a", "a", "a", "b", "b", "b"] 

132 >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst) 

133 >>> hist = ser.groupby(level=0).hist() 

134 """ 

135 plot_backend = _get_plot_backend(backend) 

136 return plot_backend.hist_series( 

137 self, 

138 by=by, 

139 ax=ax, 

140 grid=grid, 

141 xlabelsize=xlabelsize, 

142 xrot=xrot, 

143 ylabelsize=ylabelsize, 

144 yrot=yrot, 

145 figsize=figsize, 

146 bins=bins, 

147 legend=legend, 

148 **kwargs, 

149 ) 

150 

151 

152@set_module("pandas.plotting") 

153def hist_frame( 

154 data: DataFrame, 

155 column: IndexLabel | None = None, 

156 by=None, 

157 grid: bool = True, 

158 xlabelsize: int | None = None, 

159 xrot: float | None = None, 

160 ylabelsize: int | None = None, 

161 yrot: float | None = None, 

162 ax=None, 

163 sharex: bool = False, 

164 sharey: bool = False, 

165 figsize: tuple[int, int] | None = None, 

166 layout: tuple[int, int] | None = None, 

167 bins: int | Sequence[int] = 10, 

168 backend: str | None = None, 

169 legend: bool = False, 

170 **kwargs, 

171): 

172 """ 

173 Make a histogram of the DataFrame's columns. 

174 

175 A `histogram`_ is a representation of the distribution of data. 

176 This function calls :meth:`matplotlib.pyplot.hist`, on each series in 

177 the DataFrame, resulting in one histogram per column. 

178 

179 .. _histogram: https://en.wikipedia.org/wiki/Histogram 

180 

181 Parameters 

182 ---------- 

183 data : DataFrame 

184 The pandas object holding the data. 

185 column : str or sequence, optional 

186 If passed, will be used to limit data to a subset of columns. 

187 by : object, optional 

188 If passed, then used to form histograms for separate groups. 

189 grid : bool, default True 

190 Whether to show axis grid lines. 

191 xlabelsize : int, default None 

192 If specified changes the x-axis label size. 

193 xrot : float, default None 

194 Rotation of x axis labels. For example, a value of 90 displays the 

195 x labels rotated 90 degrees clockwise. 

196 ylabelsize : int, default None 

197 If specified changes the y-axis label size. 

198 yrot : float, default None 

199 Rotation of y axis labels. For example, a value of 90 displays the 

200 y labels rotated 90 degrees clockwise. 

201 ax : Matplotlib axes object, default None 

202 The axes to plot the histogram on. 

203 sharex : bool, default True if ax is None else False 

204 In case subplots=True, share x axis and set some x axis labels to 

205 invisible; defaults to True if ax is None otherwise False if an ax 

206 is passed in. 

207 Note that passing in both an ax and sharex=True will alter all x axis 

208 labels for all subplots in a figure. 

209 sharey : bool, default False 

210 In case subplots=True, share y axis and set some y axis labels to 

211 invisible. 

212 figsize : tuple, optional 

213 The size in inches of the figure to create. Uses the value in 

214 `matplotlib.rcParams` by default. 

215 layout : tuple, optional 

216 Tuple of (rows, columns) for the layout of the histograms. 

217 bins : int or sequence, default 10 

218 Number of histogram bins to be used. If an integer is given, bins + 1 

219 bin edges are calculated and returned. If bins is a sequence, gives 

220 bin edges, including left edge of first bin and right edge of last 

221 bin. In this case, bins is returned unmodified. 

222 

223 backend : str, default None 

224 Backend to use instead of the backend specified in the option 

225 ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to 

226 specify the ``plotting.backend`` for the whole session, set 

227 ``pd.options.plotting.backend``. 

228 

229 legend : bool, default False 

230 Whether to show the legend. 

231 

232 **kwargs 

233 All other plotting keyword arguments to be passed to 

234 :meth:`matplotlib.pyplot.hist`. 

235 

236 Returns 

237 ------- 

238 np.ndarray 

239 2D NumPy Array of :class:`matplotlib.axes.Axes`. 

240 

241 See Also 

242 -------- 

243 matplotlib.pyplot.hist : Plot a histogram using matplotlib. 

244 

245 Examples 

246 -------- 

247 This example draws a histogram based on the length and width of 

248 some animals, displayed in three bins 

249 

250 .. plot:: 

251 :context: close-figs 

252 

253 >>> data = { 

254 ... "length": [1.5, 0.5, 1.2, 0.9, 3], 

255 ... "width": [0.7, 0.2, 0.15, 0.2, 1.1], 

256 ... } 

257 >>> index = ["pig", "rabbit", "duck", "chicken", "horse"] 

258 >>> df = pd.DataFrame(data, index=index) 

259 >>> hist = df.hist(bins=3) 

260 """ 

261 plot_backend = _get_plot_backend(backend) 

262 return plot_backend.hist_frame( 

263 data, 

264 column=column, 

265 by=by, 

266 grid=grid, 

267 xlabelsize=xlabelsize, 

268 xrot=xrot, 

269 ylabelsize=ylabelsize, 

270 yrot=yrot, 

271 ax=ax, 

272 sharex=sharex, 

273 sharey=sharey, 

274 figsize=figsize, 

275 layout=layout, 

276 legend=legend, 

277 bins=bins, 

278 **kwargs, 

279 ) 

280 

281 

282@set_module("pandas.plotting") 

283def boxplot( 

284 data: DataFrame, 

285 column: str | list[str] | None = None, 

286 by: str | list[str] | None = None, 

287 ax: Axes | None = None, 

288 fontsize: float | str | None = None, 

289 rot: int = 0, 

290 grid: bool = True, 

291 figsize: tuple[float, float] | None = None, 

292 layout: tuple[int, int] | None = None, 

293 return_type: str | None = None, 

294 **kwargs, 

295): 

296 """ 

297 Make a box plot from DataFrame columns. 

298 

299 Make a box-and-whisker plot from DataFrame columns, optionally grouped 

300 by some other columns. A box plot is a method for graphically depicting 

301 groups of numerical data through their quartiles. 

302 The box extends from the Q1 to Q3 quartile values of the data, 

303 with a line at the median (Q2). The whiskers extend from the edges 

304 of box to show the range of the data. By default, they extend no more than 

305 `1.5 * IQR (IQR = Q3 - Q1)` from the edges of the box, ending at the farthest 

306 data point within that interval. Outliers are plotted as separate dots. 

307 

308 For further details see 

309 Wikipedia's entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`_. 

310 

311 Parameters 

312 ---------- 

313 data : DataFrame 

314 The data to visualize. 

315 column : str or list of str, optional 

316 Column name or list of names, or vector. 

317 Can be any valid input to :meth:`pandas.DataFrame.groupby`. 

318 by : str or array-like, optional 

319 Column in the DataFrame to :meth:`pandas.DataFrame.groupby`. 

320 One box-plot will be done per value of columns in `by`. 

321 ax : object of class matplotlib.axes.Axes, optional 

322 The matplotlib axes to be used by boxplot. 

323 fontsize : float or str 

324 Tick label font size in points or as a string (e.g., `large`). 

325 rot : float, default 0 

326 The rotation angle of labels (in degrees) 

327 with respect to the screen coordinate system. 

328 grid : bool, default True 

329 Setting this to True will show the grid. 

330 figsize : A tuple (width, height) in inches 

331 The size of the figure to create in matplotlib. 

332 layout : tuple (rows, columns), optional 

333 For example, (3, 5) will display the subplots 

334 using 3 rows and 5 columns, starting from the top-left. 

335 return_type : {'axes', 'dict', 'both'} or None, default 'axes' 

336 The kind of object to return. The default is ``axes``. 

337 

338 * 'axes' returns the matplotlib axes the boxplot is drawn on. 

339 * 'dict' returns a dictionary whose values are the matplotlib 

340 lines of the boxplot. 

341 * 'both' returns a namedtuple with the axes and dict. 

342 * when grouping with ``by``, a Series mapping columns to 

343 ``return_type`` is returned. 

344 

345 If ``return_type`` is `None`, a NumPy array 

346 of axes with the same shape as ``layout`` is returned. 

347 

348 **kwargs 

349 All other plotting keyword arguments to be passed to 

350 :func:`matplotlib.pyplot.boxplot`. 

351 

352 Returns 

353 ------- 

354 result 

355 See Notes. 

356 

357 See Also 

358 -------- 

359 Series.plot.hist: Make a histogram. 

360 matplotlib.pyplot.boxplot : Matplotlib equivalent plot. 

361 

362 Notes 

363 ----- 

364 The return type depends on the `return_type` parameter: 

365 

366 * 'axes' : object of class matplotlib.axes.Axes 

367 * 'dict' : dict of matplotlib.lines.Line2D objects 

368 * 'both' : a namedtuple with structure (ax, lines) 

369 

370 For data grouped with ``by``, return a Series of the above or a numpy 

371 array: 

372 

373 * :class:`~pandas.Series` 

374 * :class:`~numpy.array` (for ``return_type = None``) 

375 

376 Use ``return_type='dict'`` when you want to tweak the appearance 

377 of the lines after plotting. In this case a dict containing the Lines 

378 making up the boxes, caps, fliers, medians, and whiskers is returned. 

379 

380 Examples 

381 -------- 

382 

383 Boxplots can be created for every column in the dataframe 

384 by ``df.boxplot()`` or indicating the columns to be used: 

385 

386 .. plot:: 

387 :context: close-figs 

388 

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

390 >>> df = pd.DataFrame( 

391 ... rng.standard_normal((10, 4)), columns=["Col1", "Col2", "Col3", "Col4"] 

392 ... ) 

393 >>> boxplot = df.boxplot(column=["Col1", "Col2", "Col3"]) # doctest: +SKIP 

394 

395 Boxplots of variables distributions grouped by the values of a third 

396 variable can be created using the option ``by``. For instance: 

397 

398 .. plot:: 

399 :context: close-figs 

400 

401 >>> df = pd.DataFrame(rng.standard_normal((10, 2)), columns=["Col1", "Col2"]) 

402 >>> df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) 

403 >>> boxplot = df.boxplot(by="X") 

404 

405 A list of strings (i.e. ``['X', 'Y']``) can be passed to boxplot 

406 in order to group the data by combination of the variables in the x-axis: 

407 

408 .. plot:: 

409 :context: close-figs 

410 

411 >>> df = pd.DataFrame( 

412 ... rng.standard_normal((10, 3)), columns=["Col1", "Col2", "Col3"] 

413 ... ) 

414 >>> df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) 

415 >>> df["Y"] = pd.Series(["A", "B", "A", "B", "A", "B", "A", "B", "A", "B"]) 

416 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by=["X", "Y"]) 

417 

418 The layout of boxplot can be adjusted giving a tuple to ``layout``: 

419 

420 .. plot:: 

421 :context: close-figs 

422 

423 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by="X", layout=(2, 1)) 

424 

425 Additional formatting can be done to the boxplot, like suppressing the grid 

426 (``grid=False``), rotating the labels in the x-axis (i.e. ``rot=45``) 

427 or changing the fontsize (i.e. ``fontsize=15``): 

428 

429 .. plot:: 

430 :context: close-figs 

431 

432 >>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15) # doctest: +SKIP 

433 

434 The parameter ``return_type`` can be used to select the type of element 

435 returned by `boxplot`. When ``return_type='axes'`` is selected, 

436 the matplotlib axes on which the boxplot is drawn are returned: 

437 

438 >>> boxplot = df.boxplot(column=["Col1", "Col2"], return_type="axes") 

439 >>> type(boxplot) 

440 <class 'matplotlib.axes._axes.Axes'> 

441 

442 When grouping with ``by``, a Series mapping columns to ``return_type`` 

443 is returned: 

444 

445 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by="X", return_type="axes") 

446 >>> type(boxplot) 

447 <class 'pandas.Series'> 

448 

449 If ``return_type`` is `None`, a NumPy array of axes with the same shape 

450 as ``layout`` is returned: 

451 

452 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by="X", return_type=None) 

453 >>> type(boxplot) 

454 <class 'numpy.ndarray'> 

455 """ 

456 plot_backend = _get_plot_backend("matplotlib") 

457 return plot_backend.boxplot( 

458 data, 

459 column=column, 

460 by=by, 

461 ax=ax, 

462 fontsize=fontsize, 

463 rot=rot, 

464 grid=grid, 

465 figsize=figsize, 

466 layout=layout, 

467 return_type=return_type, 

468 **kwargs, 

469 ) 

470 

471 

472@set_module("pandas.plotting") 

473def boxplot_frame( 

474 self: DataFrame, 

475 column=None, 

476 by=None, 

477 ax=None, 

478 fontsize: int | None = None, 

479 rot: int = 0, 

480 grid: bool = True, 

481 figsize: tuple[float, float] | None = None, 

482 layout=None, 

483 return_type=None, 

484 backend=None, 

485 **kwargs, 

486): 

487 """ 

488 Make a box plot from DataFrame columns. 

489 

490 Make a box-and-whisker plot from DataFrame columns, optionally grouped 

491 by some other columns. A box plot is a method for graphically depicting 

492 groups of numerical data through their quartiles. 

493 The box extends from the Q1 to Q3 quartile values of the data, 

494 with a line at the median (Q2). The whiskers extend from the edges 

495 of box to show the range of the data. By default, they extend no more than 

496 `1.5 * IQR (IQR = Q3 - Q1)` from the edges of the box, ending at the farthest 

497 data point within that interval. Outliers are plotted as separate dots. 

498 

499 For further details see 

500 Wikipedia's entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`_. 

501 

502 Parameters 

503 ---------- 

504 column : str or list of str, optional 

505 Column name or list of names, or vector. 

506 Can be any valid input to :meth:`pandas.DataFrame.groupby`. 

507 by : str or array-like, optional 

508 Column in the DataFrame to :meth:`pandas.DataFrame.groupby`. 

509 One box-plot will be done per value of columns in `by`. 

510 ax : object of class matplotlib.axes.Axes, optional 

511 The matplotlib axes to be used by boxplot. 

512 fontsize : float or str 

513 Tick label font size in points or as a string (e.g., `large`). 

514 rot : float, default 0 

515 The rotation angle of labels (in degrees) 

516 with respect to the screen coordinate system. 

517 grid : bool, default True 

518 Setting this to True will show the grid. 

519 figsize : A tuple (width, height) in inches 

520 The size of the figure to create in matplotlib. 

521 layout : tuple (rows, columns), optional 

522 For example, (3, 5) will display the subplots 

523 using 3 rows and 5 columns, starting from the top-left. 

524 return_type : {'axes', 'dict', 'both'} or None, default 'axes' 

525 The kind of object to return. The default is ``axes``. 

526 

527 * 'axes' returns the matplotlib axes the boxplot is drawn on. 

528 * 'dict' returns a dictionary whose values are the matplotlib 

529 lines of the boxplot. 

530 * 'both' returns a namedtuple with the axes and dict. 

531 * when grouping with ``by``, a Series mapping columns to 

532 ``return_type`` is returned. 

533 

534 If ``return_type`` is `None`, a NumPy array 

535 of axes with the same shape as ``layout`` is returned. 

536 backend : str, default None 

537 Backend to use instead of the backend specified in the option 

538 ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to 

539 specify the ``plotting.backend`` for the whole session, set 

540 ``pd.options.plotting.backend``. 

541 

542 **kwargs 

543 All other plotting keyword arguments to be passed to 

544 :func:`matplotlib.pyplot.boxplot`. 

545 

546 Returns 

547 ------- 

548 result 

549 See Notes. 

550 

551 See Also 

552 -------- 

553 Series.plot.hist: Make a histogram. 

554 matplotlib.pyplot.boxplot : Matplotlib equivalent plot. 

555 

556 Notes 

557 ----- 

558 The return type depends on the `return_type` parameter: 

559 

560 * 'axes' : object of class matplotlib.axes.Axes 

561 * 'dict' : dict of matplotlib.lines.Line2D objects 

562 * 'both' : a namedtuple with structure (ax, lines) 

563 

564 For data grouped with ``by``, return a Series of the above or a numpy 

565 array: 

566 

567 * :class:`~pandas.Series` 

568 * :class:`~numpy.array` (for ``return_type = None``) 

569 

570 Use ``return_type='dict'`` when you want to tweak the appearance 

571 of the lines after plotting. In this case a dict containing the Lines 

572 making up the boxes, caps, fliers, medians, and whiskers is returned. 

573 

574 Examples 

575 -------- 

576 

577 Boxplots can be created for every column in the dataframe 

578 by ``df.boxplot()`` or indicating the columns to be used: 

579 

580 .. plot:: 

581 :context: close-figs 

582 

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

584 >>> df = pd.DataFrame( 

585 ... rng.standard_normal((10, 4)), columns=["Col1", "Col2", "Col3", "Col4"] 

586 ... ) 

587 >>> boxplot = df.boxplot(column=["Col1", "Col2", "Col3"]) # doctest: +SKIP 

588 

589 Boxplots of variables distributions grouped by the values of a third 

590 variable can be created using the option ``by``. For instance: 

591 

592 .. plot:: 

593 :context: close-figs 

594 

595 >>> df = pd.DataFrame(rng.standard_normal((10, 2)), columns=["Col1", "Col2"]) 

596 >>> df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) 

597 >>> boxplot = df.boxplot(by="X") 

598 

599 A list of strings (i.e. ``['X', 'Y']``) can be passed to boxplot 

600 in order to group the data by combination of the variables in the x-axis: 

601 

602 .. plot:: 

603 :context: close-figs 

604 

605 >>> df = pd.DataFrame( 

606 ... rng.standard_normal((10, 3)), columns=["Col1", "Col2", "Col3"] 

607 ... ) 

608 >>> df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) 

609 >>> df["Y"] = pd.Series(["A", "B", "A", "B", "A", "B", "A", "B", "A", "B"]) 

610 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by=["X", "Y"]) 

611 

612 The layout of boxplot can be adjusted giving a tuple to ``layout``: 

613 

614 .. plot:: 

615 :context: close-figs 

616 

617 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by="X", layout=(2, 1)) 

618 

619 Additional formatting can be done to the boxplot, like suppressing the grid 

620 (``grid=False``), rotating the labels in the x-axis (i.e. ``rot=45``) 

621 or changing the fontsize (i.e. ``fontsize=15``): 

622 

623 .. plot:: 

624 :context: close-figs 

625 

626 >>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15) # doctest: +SKIP 

627 

628 The parameter ``return_type`` can be used to select the type of element 

629 returned by `boxplot`. When ``return_type='axes'`` is selected, 

630 the matplotlib axes on which the boxplot is drawn are returned: 

631 

632 .. plot:: 

633 :context: close-figs 

634 

635 >>> boxplot = df.boxplot(column=["Col1", "Col2"], return_type="axes") 

636 >>> type(boxplot) 

637 <class 'matplotlib.axes._axes.Axes'> 

638 

639 When grouping with ``by``, a Series mapping columns to ``return_type`` 

640 is returned: 

641 

642 .. plot:: 

643 :context: close-figs 

644 

645 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by="X", return_type="axes") 

646 >>> type(boxplot) 

647 <class 'pandas.Series'> 

648 

649 If ``return_type`` is `None`, a NumPy array of axes with the same shape 

650 as ``layout`` is returned: 

651 

652 .. plot:: 

653 :context: close-figs 

654 

655 >>> boxplot = df.boxplot(column=["Col1", "Col2"], by="X", return_type=None) 

656 >>> type(boxplot) 

657 <class 'numpy.ndarray'> 

658 """ 

659 

660 plot_backend = _get_plot_backend(backend) 

661 return plot_backend.boxplot_frame( 

662 self, 

663 column=column, 

664 by=by, 

665 ax=ax, 

666 fontsize=fontsize, 

667 rot=rot, 

668 grid=grid, 

669 figsize=figsize, 

670 layout=layout, 

671 return_type=return_type, 

672 **kwargs, 

673 ) 

674 

675 

676@set_module("pandas.plotting") 

677def boxplot_frame_groupby( 

678 grouped: DataFrameGroupBy, 

679 subplots: bool = True, 

680 column=None, 

681 fontsize: int | None = None, 

682 rot: int = 0, 

683 grid: bool = True, 

684 ax=None, 

685 figsize: tuple[float, float] | None = None, 

686 layout=None, 

687 sharex: bool = False, 

688 sharey: bool = True, 

689 backend=None, 

690 **kwargs, 

691): 

692 """ 

693 Make box plots from DataFrameGroupBy data. 

694 

695 Creates one or more box-and-whisker plots based on data that has been 

696 grouped using :meth:`DataFrame.groupby`. Each group can be rendered as 

697 a separate subplot or combined into a single figure. 

698 

699 Parameters 

700 ---------- 

701 grouped : DataFrameGroupBy 

702 The grouped DataFrame object over which to create the box plots. 

703 subplots : bool 

704 * ``False`` - no subplots will be used 

705 * ``True`` - create a subplot for each group. 

706 column : column name or list of names, or vector 

707 Can be any valid input to groupby. 

708 fontsize : float or str 

709 Font size for the labels. 

710 rot : float 

711 Rotation angle of labels (in degrees) on the x-axis. 

712 grid : bool 

713 Whether to show grid lines on the plot. 

714 ax : Matplotlib axis object, default None 

715 The axes on which to draw the plots. If None, uses the current axes. 

716 figsize : tuple of (float, float) 

717 The figure size in inches (width, height). 

718 layout : tuple (optional) 

719 The layout of the plot: (rows, columns). 

720 sharex : bool, default False 

721 Whether x-axes will be shared among subplots. 

722 sharey : bool, default True 

723 Whether y-axes will be shared among subplots. 

724 backend : str, default None 

725 Backend to use instead of the backend specified in the option 

726 ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to 

727 specify the ``plotting.backend`` for the whole session, set 

728 ``pd.options.plotting.backend``. 

729 **kwargs 

730 All other plotting keyword arguments to be passed to 

731 matplotlib's boxplot function. 

732 

733 Returns 

734 ------- 

735 dict or DataFrame.boxplot return value 

736 If ``subplots=True``, returns a dictionary of group keys to the boxplot 

737 return values. If ``subplots=False``, returns the boxplot return value 

738 of a single DataFrame. 

739 

740 See Also 

741 -------- 

742 DataFrame.boxplot : Create a box plot from a DataFrame. 

743 Series.plot : Plot a Series. 

744 

745 Examples 

746 -------- 

747 You can create boxplots for grouped data and show them as separate subplots: 

748 

749 .. plot:: 

750 :context: close-figs 

751 

752 >>> import itertools 

753 >>> tuples = [t for t in itertools.product(range(1000), range(4))] 

754 >>> index = pd.MultiIndex.from_tuples(tuples, names=["lvl0", "lvl1"]) 

755 >>> data = np.random.default_rng(42).standard_normal((len(index), 4)) 

756 >>> df = pd.DataFrame(data, columns=list("ABCD"), index=index) 

757 >>> grouped = df.groupby(level="lvl1") 

758 >>> grouped.boxplot(rot=45, fontsize=12, figsize=(8, 10)) # doctest: +SKIP 

759 

760 The ``subplots=False`` option shows the boxplots in a single figure. 

761 

762 .. plot:: 

763 :context: close-figs 

764 

765 >>> grouped.boxplot(subplots=False, rot=45, fontsize=12) # doctest: +SKIP 

766 """ 

767 plot_backend = _get_plot_backend(backend) 

768 return plot_backend.boxplot_frame_groupby( 

769 grouped, 

770 subplots=subplots, 

771 column=column, 

772 fontsize=fontsize, 

773 rot=rot, 

774 grid=grid, 

775 ax=ax, 

776 figsize=figsize, 

777 layout=layout, 

778 sharex=sharex, 

779 sharey=sharey, 

780 **kwargs, 

781 ) 

782 

783 

784@set_module("pandas.plotting") 

785class PlotAccessor(PandasObject): 

786 """ 

787 Make plots of Series or DataFrame. 

788 

789 Uses the backend specified by the 

790 option ``plotting.backend``. By default, matplotlib is used. 

791 

792 Parameters 

793 ---------- 

794 data : Series or DataFrame 

795 The object for which the method is called. 

796 

797 Attributes 

798 ---------- 

799 x : label or position, default None 

800 Only used if data is a DataFrame. 

801 y : label, position or list of label, positions, default None 

802 Allows plotting of one column versus another. Only used if data is a 

803 DataFrame. 

804 kind : str 

805 The kind of plot to produce: 

806 

807 - 'line' : line plot (default) 

808 - 'bar' : vertical bar plot 

809 - 'barh' : horizontal bar plot 

810 - 'hist' : histogram 

811 - 'box' : boxplot 

812 - 'kde' : Kernel Density Estimation plot 

813 - 'density' : same as 'kde' 

814 - 'area' : area plot 

815 - 'pie' : pie plot 

816 - 'scatter' : scatter plot (DataFrame only) 

817 - 'hexbin' : hexbin plot (DataFrame only) 

818 by : str or sequence of str, optional 

819 Column label(s) in the DataFrame to group by. Only used if 

820 ``kind="hist"`` or ``kind="box"``; ignored for other kinds. 

821 See :meth:`DataFrame.plot.hist` and :meth:`DataFrame.plot.box`. 

822 ax : matplotlib axes object, default None 

823 The axes to plot on. If None, ``Series.plot`` draws on the 

824 current axes (``matplotlib.pyplot.gca()``) when a figure already 

825 exists, while ``DataFrame.plot`` always creates a new figure. 

826 subplots : bool or sequence of iterables, default False 

827 Whether to group columns into subplots: 

828 

829 - ``False`` : No subplots will be used 

830 - ``True`` : Make separate subplots for each column. 

831 - sequence of iterables of column labels: Create a subplot for each 

832 group of columns. For example `[('a', 'c'), ('b', 'd')]` will 

833 create 2 subplots: one with columns 'a' and 'c', and one 

834 with columns 'b' and 'd'. Remaining columns that aren't specified 

835 will be plotted in additional subplots (one per column). 

836 

837 sharex : bool, default True if ax is None else False 

838 In case ``subplots=True``, share x axis and set some x axis labels 

839 to invisible; defaults to True if ax is None otherwise False if 

840 an ax is passed in; Be aware, that passing in both an ax and 

841 ``sharex=True`` will alter all x axis labels for all axis in a figure. 

842 sharey : bool, default False 

843 In case ``subplots=True``, share y axis and set some y axis labels to invisible. 

844 layout : tuple, optional 

845 (rows, columns) for the layout of subplots. 

846 figsize : a tuple (width, height) in inches 

847 Size of a figure object. 

848 use_index : bool, default True 

849 Use index as ticks for x axis. 

850 title : str or list 

851 Title to use for the plot. If a string is passed, print the string 

852 at the top of the figure. If a list is passed and `subplots` is 

853 True, print each item in the list above the corresponding subplot. 

854 grid : bool, default None (matlab style default) 

855 Axis grid lines. 

856 legend : bool or {'reverse'} 

857 Place legend on axis subplots. 

858 style : list or dict 

859 The matplotlib line style per column. 

860 logx : bool or 'sym', default False 

861 Use log scaling or symlog scaling on x axis. 

862 

863 logy : bool or 'sym' default False 

864 Use log scaling or symlog scaling on y axis. 

865 

866 loglog : bool or 'sym', default False 

867 Use log scaling or symlog scaling on both x and y axes. 

868 

869 xticks : sequence 

870 Values to use for the xticks. 

871 yticks : sequence 

872 Values to use for the yticks. 

873 xlim : 2-tuple/list 

874 Set the x limits of the current axes. 

875 ylim : 2-tuple/list 

876 Set the y limits of the current axes. 

877 xlabel : label, optional 

878 Name to use for the xlabel on x-axis. Default uses index name as xlabel, or the 

879 x-column name for planar plots. 

880 

881 .. versionchanged:: 2.0.0 

882 

883 Now applicable to histograms. 

884 

885 ylabel : label, optional 

886 Name to use for the ylabel on y-axis. Default will show no ylabel, or the 

887 y-column name for planar plots. 

888 

889 .. versionchanged:: 2.0.0 

890 

891 Now applicable to histograms. 

892 

893 rot : float, default None 

894 Rotation for ticks (xticks for vertical, yticks for horizontal 

895 plots). 

896 fontsize : float, default None 

897 Font size for xticks and yticks. 

898 colormap : str or matplotlib colormap object, default None 

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

900 name from matplotlib. 

901 color : str, array-like, or dict, optional 

902 Color for the plot elements when using the default ``matplotlib`` 

903 backend. Supported for ``kind`` values ``"line"``, ``"bar"``, 

904 ``"barh"``, ``"hist"``, ``"kde"``, ``"density"``, ``"area"``, 

905 ``"box"``, and ``"scatter"``. A dict maps DataFrame column names to 

906 colors except for box and scatter plots. For box plots, a dict maps 

907 ``"boxes"``, ``"whiskers"``, ``"medians"``, and ``"caps"`` to colors. 

908 For scatter plots, an array-like specifies the color of each point. 

909 colorbar : bool, optional 

910 If True, plot colorbar (only relevant for 'scatter' and 'hexbin' 

911 plots). 

912 position : float 

913 Specify relative alignments for bar plot layout. 

914 From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 

915 (center). 

916 table : bool, Series or DataFrame, default False 

917 If True, draw a table using the data in the DataFrame and the data 

918 will be transposed to meet matplotlib's default layout. 

919 If a Series or DataFrame is passed, use passed data to draw a 

920 table. 

921 yerr : DataFrame, Series, array-like, dict and str 

922 See :ref:`Plotting with Error Bars <visualization.errorbars>` for 

923 detail. 

924 xerr : DataFrame, Series, array-like, dict and str 

925 Equivalent to yerr. 

926 stacked : bool, default False in line and bar plots, and True in area plot 

927 If True, create stacked plot. 

928 secondary_y : bool or sequence, default False 

929 Whether to plot on the secondary y-axis if a list/tuple, which 

930 columns to plot on secondary y-axis. 

931 mark_right : bool, default True 

932 When using a secondary_y axis, automatically mark the column 

933 labels with "(right)" in the legend. 

934 include_bool : bool, default is False 

935 If True, boolean values can be plotted. 

936 backend : str, default None 

937 Backend to use instead of the backend specified in the option 

938 ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to 

939 specify the ``plotting.backend`` for the whole session, set 

940 ``pd.options.plotting.backend``. 

941 **kwargs 

942 Options to pass to matplotlib plotting method. 

943 

944 Returns 

945 ------- 

946 :class:`matplotlib.axes.Axes` or numpy.ndarray of them 

947 If the backend is not the default matplotlib one, the return value 

948 will be the object returned by the backend. 

949 

950 See Also 

951 -------- 

952 matplotlib.pyplot.plot : Plot y versus x as lines and/or markers. 

953 DataFrame.hist : Make a histogram. 

954 DataFrame.boxplot : Make a box plot. 

955 DataFrame.plot.scatter : Make a scatter plot with varying marker 

956 point size and color. 

957 DataFrame.plot.hexbin : Make a hexagonal binning plot of 

958 two variables. 

959 DataFrame.plot.kde : Make Kernel Density Estimate plot using 

960 Gaussian kernels. 

961 DataFrame.plot.area : Make a stacked area plot. 

962 DataFrame.plot.bar : Make a bar plot. 

963 DataFrame.plot.barh : Make a horizontal bar plot. 

964 

965 Notes 

966 ----- 

967 - See matplotlib documentation online for more on this subject 

968 - If `kind` = 'bar' or 'barh', you can specify relative alignments 

969 for bar plot layout by `position` keyword. 

970 From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 

971 (center) 

972 

973 Examples 

974 -------- 

975 For Series: 

976 

977 .. plot:: 

978 :context: close-figs 

979 

980 >>> ser = pd.Series([1, 2, 3, 3]) 

981 >>> plot = ser.plot(kind="hist", title="My plot") 

982 

983 For DataFrame: 

984 

985 .. plot:: 

986 :context: close-figs 

987 

988 >>> df = pd.DataFrame( 

989 ... { 

990 ... "length": [1.5, 0.5, 1.2, 0.9, 3], 

991 ... "width": [0.7, 0.2, 0.15, 0.2, 1.1], 

992 ... }, 

993 ... index=["pig", "rabbit", "duck", "chicken", "horse"], 

994 ... ) 

995 >>> plot = df.plot(title="DataFrame Plot") 

996 

997 For SeriesGroupBy: 

998 

999 .. plot:: 

1000 :context: close-figs 

1001 

1002 >>> lst = [-1, -2, -3, 1, 2, 3] 

1003 >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst) 

1004 >>> plot = ser.groupby(lambda x: x > 0).plot(title="SeriesGroupBy Plot") 

1005 

1006 For DataFrameGroupBy: 

1007 

1008 .. plot:: 

1009 :context: close-figs 

1010 

1011 >>> df = pd.DataFrame({"col1": [1, 2, 3, 4], "col2": ["A", "B", "A", "B"]}) 

1012 >>> plot = df.groupby("col2").plot(kind="bar", title="DataFrameGroupBy Plot") 

1013 """ 

1014 

1015 _common_kinds = ("line", "bar", "barh", "kde", "density", "area", "hist", "box") 

1016 _series_kinds = ("pie",) 

1017 _dataframe_kinds = ("scatter", "hexbin") 

1018 _kind_aliases = {"density": "kde"} 

1019 _all_kinds = _common_kinds + _series_kinds + _dataframe_kinds 

1020 

1021 def __init__(self, data: Series | DataFrame) -> None: 

1022 self._parent = data 

1023 

1024 @staticmethod 

1025 def _get_call_args(backend_name: str, data: Series | DataFrame, args, kwargs): 

1026 """ 

1027 This function makes calls to this accessor `__call__` method compatible 

1028 with the previous `SeriesPlotMethods.__call__` and 

1029 `DataFramePlotMethods.__call__`. Those had slightly different 

1030 signatures, since `DataFramePlotMethods` accepted `x` and `y` 

1031 parameters. 

1032 """ 

1033 if isinstance(data, ABCSeries): 

1034 arg_def = [ 

1035 ("kind", "line"), 

1036 ("ax", None), 

1037 ("figsize", None), 

1038 ("use_index", True), 

1039 ("title", None), 

1040 ("grid", None), 

1041 ("legend", False), 

1042 ("style", None), 

1043 ("logx", False), 

1044 ("logy", False), 

1045 ("loglog", False), 

1046 ("xticks", None), 

1047 ("yticks", None), 

1048 ("xlim", None), 

1049 ("ylim", None), 

1050 ("rot", None), 

1051 ("fontsize", None), 

1052 ("colormap", None), 

1053 ("table", False), 

1054 ("yerr", None), 

1055 ("xerr", None), 

1056 ("label", None), 

1057 ("secondary_y", False), 

1058 ("xlabel", None), 

1059 ("ylabel", None), 

1060 ] 

1061 elif isinstance(data, ABCDataFrame): 

1062 arg_def = [ 

1063 ("x", None), 

1064 ("y", None), 

1065 ("kind", "line"), 

1066 ("ax", None), 

1067 ("subplots", False), 

1068 ("sharex", None), 

1069 ("sharey", False), 

1070 ("layout", None), 

1071 ("figsize", None), 

1072 ("use_index", True), 

1073 ("title", None), 

1074 ("grid", None), 

1075 ("legend", True), 

1076 ("style", None), 

1077 ("logx", False), 

1078 ("logy", False), 

1079 ("loglog", False), 

1080 ("xticks", None), 

1081 ("yticks", None), 

1082 ("xlim", None), 

1083 ("ylim", None), 

1084 ("rot", None), 

1085 ("fontsize", None), 

1086 ("colormap", None), 

1087 ("table", False), 

1088 ("yerr", None), 

1089 ("xerr", None), 

1090 ("secondary_y", False), 

1091 ("xlabel", None), 

1092 ("ylabel", None), 

1093 ] 

1094 else: 

1095 raise TypeError( 

1096 f"Called plot accessor for type {type(data).__name__}, " 

1097 "expected Series or DataFrame" 

1098 ) 

1099 

1100 if args and isinstance(data, ABCSeries): 

1101 positional_args = str(args)[1:-1] 

1102 keyword_args = ", ".join( 

1103 [ 

1104 f"{name}={value!r}" 

1105 for (name, _), value in zip(arg_def, args, strict=False) 

1106 ] 

1107 ) 

1108 msg = ( 

1109 "`Series.plot()` should not be called with positional " 

1110 "arguments, only keyword arguments. The order of " 

1111 "positional arguments will change in the future. " 

1112 f"Use `Series.plot({keyword_args})` instead of " 

1113 f"`Series.plot({positional_args})`." 

1114 ) 

1115 raise TypeError(msg) 

1116 

1117 pos_args = { 

1118 name: value for (name, _), value in zip(arg_def, args, strict=False) 

1119 } 

1120 if backend_name == "pandas.plotting._matplotlib": 

1121 kwargs = dict(arg_def, **pos_args, **kwargs) 

1122 else: 

1123 kwargs = dict(pos_args, **kwargs) 

1124 

1125 x = kwargs.pop("x", None) 

1126 y = kwargs.pop("y", None) 

1127 kind = kwargs.pop("kind", "line") 

1128 return x, y, kind, kwargs 

1129 

1130 def __call__(self, *args, **kwargs): 

1131 """ 

1132 Make plots of Series or DataFrame. 

1133 

1134 Uses the backend specified by the 

1135 option ``plotting.backend``. By default, matplotlib is used. 

1136 

1137 Parameters 

1138 ---------- 

1139 *args 

1140 Positional arguments to pass to the plotting backend. 

1141 **kwargs 

1142 Keyword arguments to pass to the plotting backend. 

1143 

1144 Attributes 

1145 ---------- 

1146 x : label or position, default None 

1147 Only used if data is a DataFrame. 

1148 y : label, position or list of label, positions, default None 

1149 Allows plotting of one column versus another. Only used if data is a 

1150 DataFrame. 

1151 kind : str 

1152 The kind of plot to produce: 

1153 

1154 - 'line' : line plot (default) 

1155 - 'bar' : vertical bar plot 

1156 - 'barh' : horizontal bar plot 

1157 - 'hist' : histogram 

1158 - 'box' : boxplot 

1159 - 'kde' : Kernel Density Estimation plot 

1160 - 'density' : same as 'kde' 

1161 - 'area' : area plot 

1162 - 'pie' : pie plot 

1163 - 'scatter' : scatter plot (DataFrame only) 

1164 - 'hexbin' : hexbin plot (DataFrame only) 

1165 by : str or sequence of str, optional 

1166 Column label(s) in the DataFrame to group by. Only used if 

1167 ``kind="hist"`` or ``kind="box"``; ignored for other kinds. 

1168 See :meth:`DataFrame.plot.hist` and :meth:`DataFrame.plot.box`. 

1169 ax : matplotlib axes object, default None 

1170 The axes to plot on. If None, ``Series.plot`` draws on the 

1171 current axes (``matplotlib.pyplot.gca()``) when a figure already 

1172 exists, while ``DataFrame.plot`` always creates a new figure. 

1173 subplots : bool or sequence of iterables, default False 

1174 Whether to group columns into subplots: 

1175 

1176 - ``False`` : No subplots will be used 

1177 - ``True`` : Make separate subplots for each column. 

1178 - sequence of iterables of column labels: Create a subplot for each 

1179 group of columns. For example `[('a', 'c'), ('b', 'd')]` will 

1180 create 2 subplots: one with columns 'a' and 'c', and one 

1181 with columns 'b' and 'd'. Remaining columns that aren't specified 

1182 will be plotted in additional subplots (one per column). 

1183 

1184 sharex : bool, default True if ax is None else False 

1185 In case ``subplots=True``, share x axis and set some x axis labels 

1186 to invisible; defaults to True if ax is None otherwise False if 

1187 an ax is passed in; Be aware, that passing in both an ax and 

1188 ``sharex=True`` will alter all x axis labels for all axis in a 

1189 figure. 

1190 sharey : bool, default False 

1191 In case ``subplots=True``, share y axis and set some y axis labels 

1192 to invisible. 

1193 layout : tuple, optional 

1194 (rows, columns) for the layout of subplots. 

1195 figsize : a tuple (width, height) in inches 

1196 Size of a figure object. 

1197 use_index : bool, default True 

1198 Use index as ticks for x axis. 

1199 title : str or list 

1200 Title to use for the plot. If a string is passed, print the string 

1201 at the top of the figure. If a list is passed and `subplots` is 

1202 True, print each item in the list above the corresponding subplot. 

1203 grid : bool, default None (matlab style default) 

1204 Axis grid lines. 

1205 legend : bool or {'reverse'} 

1206 Place legend on axis subplots. 

1207 style : list or dict 

1208 The matplotlib line style per column. 

1209 logx : bool or 'sym', default False 

1210 Use log scaling or symlog scaling on x axis. 

1211 

1212 logy : bool or 'sym' default False 

1213 Use log scaling or symlog scaling on y axis. 

1214 

1215 loglog : bool or 'sym', default False 

1216 Use log scaling or symlog scaling on both x and y axes. 

1217 

1218 xticks : sequence 

1219 Values to use for the xticks. 

1220 yticks : sequence 

1221 Values to use for the yticks. 

1222 xlim : 2-tuple/list 

1223 Set the x limits of the current axes. 

1224 ylim : 2-tuple/list 

1225 Set the y limits of the current axes. 

1226 xlabel : label, optional 

1227 Name to use for the xlabel on x-axis. Default uses index name as 

1228 xlabel, or the x-column name for planar plots. 

1229 

1230 .. versionchanged:: 2.0.0 

1231 

1232 Now applicable to histograms. 

1233 

1234 ylabel : label, optional 

1235 Name to use for the ylabel on y-axis. Default will show no ylabel, 

1236 or the y-column name for planar plots. 

1237 

1238 .. versionchanged:: 2.0.0 

1239 

1240 Now applicable to histograms. 

1241 

1242 rot : float, default None 

1243 Rotation for ticks (xticks for vertical, yticks for horizontal 

1244 plots). 

1245 fontsize : float, default None 

1246 Font size for xticks and yticks. 

1247 colormap : str or matplotlib colormap object, default None 

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

1249 name from matplotlib. 

1250 colorbar : bool, optional 

1251 If True, plot colorbar (only relevant for 'scatter' and 'hexbin' 

1252 plots). 

1253 position : float 

1254 Specify relative alignments for bar plot layout. 

1255 From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 

1256 (center). 

1257 table : bool, Series or DataFrame, default False 

1258 If True, draw a table using the data in the DataFrame and the data 

1259 will be transposed to meet matplotlib's default layout. 

1260 If a Series or DataFrame is passed, use passed data to draw a 

1261 table. 

1262 yerr : DataFrame, Series, array-like, dict and str 

1263 See :ref:`Plotting with Error Bars <visualization.errorbars>` for 

1264 detail. 

1265 xerr : DataFrame, Series, array-like, dict and str 

1266 Equivalent to yerr. 

1267 stacked : bool, default False in line and bar plots, and True in area plot 

1268 If True, create stacked plot. 

1269 secondary_y : bool or sequence, default False 

1270 Whether to plot on the secondary y-axis if a list/tuple, which 

1271 columns to plot on secondary y-axis. 

1272 mark_right : bool, default True 

1273 When using a secondary_y axis, automatically mark the column 

1274 labels with "(right)" in the legend. 

1275 include_bool : bool, default is False 

1276 If True, boolean values can be plotted. 

1277 backend : str, default None 

1278 Backend to use instead of the backend specified in the option 

1279 ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to 

1280 specify the ``plotting.backend`` for the whole session, set 

1281 ``pd.options.plotting.backend``. 

1282 

1283 Returns 

1284 ------- 

1285 :class:`matplotlib.axes.Axes` or numpy.ndarray of them 

1286 If the backend is not the default matplotlib one, the return value 

1287 will be the object returned by the backend. 

1288 

1289 See Also 

1290 -------- 

1291 matplotlib.pyplot.plot : Plot y versus x as lines and/or markers. 

1292 DataFrame.hist : Make a histogram. 

1293 DataFrame.boxplot : Make a box plot. 

1294 DataFrame.plot.scatter : Make a scatter plot with varying marker 

1295 point size and color. 

1296 DataFrame.plot.hexbin : Make a hexagonal binning plot of 

1297 two variables. 

1298 DataFrame.plot.kde : Make Kernel Density Estimate plot using 

1299 Gaussian kernels. 

1300 DataFrame.plot.area : Make a stacked area plot. 

1301 DataFrame.plot.bar : Make a bar plot. 

1302 DataFrame.plot.barh : Make a horizontal bar plot. 

1303 

1304 Notes 

1305 ----- 

1306 - See matplotlib documentation online for more on this subject 

1307 - If `kind` = 'bar' or 'barh', you can specify relative alignments 

1308 for bar plot layout by `position` keyword. 

1309 From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 

1310 (center) 

1311 

1312 Examples 

1313 -------- 

1314 For Series: 

1315 

1316 .. plot:: 

1317 :context: close-figs 

1318 

1319 >>> ser = pd.Series([1, 2, 3, 3]) 

1320 >>> plot = ser.plot(kind="hist", title="My plot") 

1321 

1322 For DataFrame: 

1323 

1324 .. plot:: 

1325 :context: close-figs 

1326 

1327 >>> df = pd.DataFrame( 

1328 ... { 

1329 ... "length": [1.5, 0.5, 1.2, 0.9, 3], 

1330 ... "width": [0.7, 0.2, 0.15, 0.2, 1.1], 

1331 ... }, 

1332 ... index=["pig", "rabbit", "duck", "chicken", "horse"], 

1333 ... ) 

1334 >>> plot = df.plot(title="DataFrame Plot") 

1335 

1336 For SeriesGroupBy: 

1337 

1338 .. plot:: 

1339 :context: close-figs 

1340 

1341 >>> lst = [-1, -2, -3, 1, 2, 3] 

1342 >>> ser = pd.Series([1, 2, 2, 4, 6, 6], index=lst) 

1343 >>> plot = ser.groupby(lambda x: x > 0).plot(title="SeriesGroupBy Plot") 

1344 

1345 For DataFrameGroupBy: 

1346 

1347 .. plot:: 

1348 :context: close-figs 

1349 

1350 >>> df = pd.DataFrame({"col1": [1, 2, 3, 4], "col2": ["A", "B", "A", "B"]}) 

1351 >>> plot = df.groupby("col2").plot( 

1352 ... kind="bar", title="DataFrameGroupBy Plot" 

1353 ... ) 

1354 """ 

1355 plot_backend = _get_plot_backend(kwargs.pop("backend", None)) 

1356 

1357 x, y, kind, kwargs = self._get_call_args( 

1358 plot_backend.__name__, self._parent, args, kwargs 

1359 ) 

1360 

1361 kind = self._kind_aliases.get(kind, kind) 

1362 

1363 # when using another backend, get out of the way 

1364 if plot_backend.__name__ != "pandas.plotting._matplotlib": 

1365 return plot_backend.plot(self._parent, x=x, y=y, kind=kind, **kwargs) 

1366 

1367 if kind not in self._all_kinds: 

1368 raise ValueError( 

1369 f"{kind} is not a valid plot kind Valid plot kinds: {self._all_kinds}" 

1370 ) 

1371 

1372 data = self._parent 

1373 

1374 if isinstance(data, ABCSeries): 

1375 kwargs["reuse_plot"] = True 

1376 

1377 if kind in self._dataframe_kinds: 

1378 if isinstance(data, ABCDataFrame): 

1379 return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs) 

1380 else: 

1381 raise ValueError(f"plot kind {kind} can only be used for data frames") 

1382 elif kind in self._series_kinds: 

1383 if isinstance(data, ABCDataFrame): 

1384 if y is None and kwargs.get("subplots") is False: 

1385 raise ValueError( 

1386 f"{kind} requires either y column or 'subplots=True'" 

1387 ) 

1388 if y is not None: 

1389 if is_integer(y) and not holds_integer(data.columns): 

1390 y = data.columns[y] 

1391 # converted to series actually. copy to not modify 

1392 data = data[y].copy(deep=False) 

1393 data.index.name = y 

1394 elif isinstance(data, ABCDataFrame): 

1395 data_cols = data.columns 

1396 if x is not None: 

1397 if is_integer(x) and not holds_integer(data.columns): 

1398 x = data_cols[x] 

1399 elif not isinstance(data[x], ABCSeries): 

1400 raise ValueError("x must be a label or position") 

1401 data = data.set_index(x) 

1402 if y is not None: 

1403 # check if we have y as int or list of ints 

1404 int_ylist = is_list_like(y) and all(is_integer(c) for c in y) 

1405 int_y_arg = is_integer(y) or int_ylist 

1406 if int_y_arg and not holds_integer(data.columns): 

1407 y = data_cols[y] 

1408 

1409 label_kw = kwargs["label"] if "label" in kwargs else False 

1410 for kw in ["xerr", "yerr"]: 

1411 if kw in kwargs and ( 

1412 isinstance(kwargs[kw], str) or is_integer(kwargs[kw]) 

1413 ): 

1414 try: 

1415 kwargs[kw] = data[kwargs[kw]] 

1416 except (IndexError, KeyError, TypeError): 

1417 pass 

1418 

1419 data = data[y] 

1420 

1421 if isinstance(data, ABCSeries): 

1422 label_name = label_kw or y 

1423 data.name = label_name 

1424 else: 

1425 # error: Argument 1 to "len" has incompatible type "Any | bool"; 

1426 # expected "Sized" [arg-type] 

1427 match = is_list_like(label_kw) and len(label_kw) == len(y) # type: ignore[arg-type] 

1428 if label_kw and not match: 

1429 raise ValueError( 

1430 "label should be list-like and same length as y" 

1431 ) 

1432 label_name = label_kw or data.columns 

1433 data.columns = label_name 

1434 

1435 return plot_backend.plot(data, kind=kind, **kwargs) 

1436 

1437 def line( 

1438 self, 

1439 x: Hashable | None = None, 

1440 y: Hashable | None = None, 

1441 color: str | Sequence[str] | dict[Hashable, str] | None = None, 

1442 **kwargs, 

1443 ) -> PlotAccessor: 

1444 """ 

1445 Make a line plot of a Series or DataFrame. 

1446 

1447 This function is useful to plot lines using DataFrame's values 

1448 as coordinates. 

1449 

1450 Parameters 

1451 ---------- 

1452 x : label or position, optional 

1453 Allows plotting of one column versus another. If not specified, 

1454 the index of the DataFrame is used. 

1455 y : label or position, optional 

1456 Allows plotting of one column versus another. If not specified, 

1457 all numerical columns are used. 

1458 color : str, array-like, or dict, optional 

1459 The color for each of the DataFrame's columns. Possible values are: 

1460 

1461 - A single color string referred to by name, RGB or RGBA code, 

1462 for instance 'red' or '#a98d19'. 

1463 

1464 - A sequence of color strings referred to by name, RGB or RGBA 

1465 code, which will be used for each column recursively. For 

1466 instance ['green','yellow'] each column's line will be filled in 

1467 green or yellow, alternatively. If there is only a single column to 

1468 be plotted, then only the first color from the color list will be 

1469 used. 

1470 

1471 - A dict of the form {column name : color}, so that each column will be 

1472 colored accordingly. For example, if your columns are called `a` and 

1473 `b`, then passing {'a': 'green', 'b': 'red'} will color lines for 

1474 column `a` in green and lines for column `b` in red. 

1475 

1476 **kwargs 

1477 Additional keyword arguments, such as ``ax``, ``figsize``, 

1478 ``title`` and ``legend``, are documented in 

1479 :meth:`DataFrame.plot`. In addition, passing ``x_compat=True`` 

1480 suppresses pandas' automatic tick resolution adjustment for 

1481 regular frequency time-series data in favor of the default 

1482 matplotlib tick locators and formatters. See 

1483 :ref:`Suppressing tick resolution adjustment 

1484 <plotting.x_compat>` for more. 

1485 

1486 Returns 

1487 ------- 

1488 matplotlib.axes.Axes or numpy.ndarray of them 

1489 An ndarray of :class:`matplotlib.axes.Axes` is returned when 

1490 ``subplots=True``. 

1491 

1492 See Also 

1493 -------- 

1494 DataFrame.plot : Make plots of a DataFrame. 

1495 matplotlib.pyplot.plot : Plot y versus x as lines and/or markers. 

1496 

1497 Examples 

1498 -------- 

1499 

1500 .. plot:: 

1501 :context: close-figs 

1502 

1503 >>> s = pd.Series([1, 3, 2]) 

1504 >>> s.plot.line() # doctest: +SKIP 

1505 

1506 .. plot:: 

1507 :context: close-figs 

1508 

1509 The following example shows the populations for some animals 

1510 over the years. 

1511 

1512 >>> df = pd.DataFrame( 

1513 ... { 

1514 ... "pig": [20, 18, 489, 675, 1776], 

1515 ... "horse": [4, 25, 281, 600, 1900], 

1516 ... }, 

1517 ... index=[1990, 1997, 2003, 2009, 2014], 

1518 ... ) 

1519 >>> lines = df.plot.line() 

1520 

1521 .. plot:: 

1522 :context: close-figs 

1523 

1524 An example with subplots, so an array of axes is returned. 

1525 

1526 >>> axes = df.plot.line(subplots=True) 

1527 >>> type(axes) 

1528 <class 'numpy.ndarray'> 

1529 

1530 .. plot:: 

1531 :context: close-figs 

1532 

1533 Let's repeat the same example, but specifying colors for 

1534 each column (in this case, for each animal). 

1535 

1536 >>> axes = df.plot.line( 

1537 ... subplots=True, color={"pig": "pink", "horse": "#742802"} 

1538 ... ) 

1539 

1540 .. plot:: 

1541 :context: close-figs 

1542 

1543 The following example shows the relationship between both 

1544 populations. 

1545 

1546 >>> lines = df.plot.line(x="pig", y="horse") 

1547 """ 

1548 if color is not None: 

1549 kwargs["color"] = color 

1550 return self(kind="line", x=x, y=y, **kwargs) 

1551 

1552 def bar( 

1553 self, 

1554 x: Hashable | None = None, 

1555 y: Hashable | None = None, 

1556 color: str | Sequence[str] | dict[Hashable, str] | None = None, 

1557 **kwargs, 

1558 ) -> PlotAccessor: 

1559 """ 

1560 Make a vertical bar plot. 

1561 

1562 A bar plot is a plot that presents categorical data with 

1563 rectangular bars with lengths proportional to the values that they 

1564 represent. A bar plot shows comparisons among discrete categories. One 

1565 axis of the plot shows the specific categories being compared, and the 

1566 other axis represents a measured value. 

1567 

1568 Parameters 

1569 ---------- 

1570 x : label or position, optional 

1571 Allows plotting of one column versus another. If not specified, 

1572 the index of the DataFrame is used. 

1573 y : label or position, optional 

1574 Allows plotting of one column versus another. If not specified, 

1575 all numerical columns are used. 

1576 color : str, array-like, or dict, optional 

1577 The color for each of the DataFrame's columns. Possible values are: 

1578 

1579 - A single color string referred to by name, RGB or RGBA code, 

1580 for instance 'red' or '#a98d19'. 

1581 

1582 - A sequence of color strings referred to by name, RGB or RGBA 

1583 code, which will be used for each column recursively. For 

1584 instance ['green','yellow'] each column's bar will be filled in 

1585 green or yellow, alternatively. If there is only a single column to 

1586 be plotted, then only the first color from the color list will be 

1587 used. 

1588 

1589 - A dict of the form {column name : color}, so that each column will be 

1590 colored accordingly. For example, if your columns are called `a` and 

1591 `b`, then passing {'a': 'green', 'b': 'red'} will color bars for 

1592 column `a` in green and bars for column `b` in red. 

1593 

1594 **kwargs 

1595 Additional keyword arguments, such as ``ax``, ``figsize``, 

1596 ``title`` and ``legend``, are documented in 

1597 :meth:`DataFrame.plot`. 

1598 

1599 Returns 

1600 ------- 

1601 matplotlib.axes.Axes or numpy.ndarray of them 

1602 An ndarray of :class:`matplotlib.axes.Axes` is returned when 

1603 ``subplots=True``. 

1604 

1605 See Also 

1606 -------- 

1607 DataFrame.plot.barh : Horizontal bar plot. 

1608 DataFrame.plot : Make plots of a DataFrame. 

1609 matplotlib.pyplot.bar : Make a bar plot with matplotlib. 

1610 

1611 Notes 

1612 ----- 

1613 A bar plot draws one tick label per bar, i.e. one per row of the data. 

1614 This differs from a line plot, where the axis uses an automatic locator 

1615 that shows only a subset of evenly spaced ticks. With many bars the 

1616 labels may therefore overlap; set the tick positions and labels manually 

1617 (e.g. via ``ax.set_xticks``) if a sparser axis is desired. 

1618 

1619 Examples 

1620 -------- 

1621 Basic plot. 

1622 

1623 .. plot:: 

1624 :context: close-figs 

1625 

1626 >>> df = pd.DataFrame({"lab": ["A", "B", "C"], "val": [10, 30, 20]}) 

1627 >>> ax = df.plot.bar(x="lab", y="val", rot=0) 

1628 

1629 Plot a whole dataframe to a bar plot. Each column is assigned a 

1630 distinct color, and each row is nested in a group along the 

1631 horizontal axis. 

1632 

1633 .. plot:: 

1634 :context: close-figs 

1635 

1636 >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] 

1637 >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] 

1638 >>> index = [ 

1639 ... "snail", 

1640 ... "pig", 

1641 ... "elephant", 

1642 ... "rabbit", 

1643 ... "giraffe", 

1644 ... "coyote", 

1645 ... "horse", 

1646 ... ] 

1647 >>> df = pd.DataFrame({"speed": speed, "lifespan": lifespan}, index=index) 

1648 >>> ax = df.plot.bar(rot=0) 

1649 

1650 Plot stacked bar charts for the DataFrame 

1651 

1652 .. plot:: 

1653 :context: close-figs 

1654 

1655 >>> ax = df.plot.bar(stacked=True) 

1656 

1657 Instead of nesting, the figure can be split by column with 

1658 ``subplots=True``. In this case, a :class:`numpy.ndarray` of 

1659 :class:`matplotlib.axes.Axes` are returned. 

1660 

1661 .. plot:: 

1662 :context: close-figs 

1663 

1664 >>> axes = df.plot.bar(rot=0, subplots=True) 

1665 >>> axes[1].legend(loc=2) # doctest: +SKIP 

1666 

1667 If you don't like the default colours, you can specify how you'd 

1668 like each column to be colored. 

1669 

1670 .. plot:: 

1671 :context: close-figs 

1672 

1673 >>> axes = df.plot.bar( 

1674 ... rot=0, 

1675 ... subplots=True, 

1676 ... color={"speed": "red", "lifespan": "green"}, 

1677 ... ) 

1678 >>> axes[1].legend(loc=2) # doctest: +SKIP 

1679 

1680 Plot a single column. 

1681 

1682 .. plot:: 

1683 :context: close-figs 

1684 

1685 >>> ax = df.plot.bar(y="speed", rot=0) 

1686 

1687 Plot only selected categories for the DataFrame. 

1688 

1689 .. plot:: 

1690 :context: close-figs 

1691 

1692 >>> ax = df.plot.bar(x="lifespan", rot=0) 

1693 """ 

1694 if color is not None: 

1695 kwargs["color"] = color 

1696 return self(kind="bar", x=x, y=y, **kwargs) 

1697 

1698 def barh( 

1699 self, 

1700 x: Hashable | None = None, 

1701 y: Hashable | None = None, 

1702 color: str | Sequence[str] | dict[Hashable, str] | None = None, 

1703 **kwargs, 

1704 ) -> PlotAccessor: 

1705 """ 

1706 Make a horizontal bar plot. 

1707 

1708 A horizontal bar plot is a plot that presents quantitative data with 

1709 rectangular bars with lengths proportional to the values that they 

1710 represent. A bar plot shows comparisons among discrete categories. One 

1711 axis of the plot shows the specific categories being compared, and the 

1712 other axis represents a measured value. 

1713 

1714 Parameters 

1715 ---------- 

1716 x : label or position, optional 

1717 Allows plotting of one column versus another. If not specified, 

1718 the index of the DataFrame is used. 

1719 y : label or position, optional 

1720 Allows plotting of one column versus another. If not specified, 

1721 all numerical columns are used. 

1722 color : str, array-like, or dict, optional 

1723 The color for each of the DataFrame's columns. Possible values are: 

1724 

1725 - A single color string referred to by name, RGB or RGBA code, 

1726 for instance 'red' or '#a98d19'. 

1727 

1728 - A sequence of color strings referred to by name, RGB or RGBA 

1729 code, which will be used for each column recursively. For 

1730 instance ['green','yellow'] each column's bar will be filled in 

1731 green or yellow, alternatively. If there is only a single column to 

1732 be plotted, then only the first color from the color list will be 

1733 used. 

1734 

1735 - A dict of the form {column name : color}, so that each column will be 

1736 colored accordingly. For example, if your columns are called `a` and 

1737 `b`, then passing {'a': 'green', 'b': 'red'} will color bars for 

1738 column `a` in green and bars for column `b` in red. 

1739 

1740 **kwargs 

1741 Additional keyword arguments, such as ``ax``, ``figsize``, 

1742 ``title`` and ``legend``, are documented in 

1743 :meth:`DataFrame.plot`. 

1744 

1745 Returns 

1746 ------- 

1747 matplotlib.axes.Axes or numpy.ndarray of them 

1748 An ndarray of :class:`matplotlib.axes.Axes` is returned when 

1749 ``subplots=True``. 

1750 

1751 See Also 

1752 -------- 

1753 DataFrame.plot.bar : Vertical bar plot. 

1754 DataFrame.plot : Make plots of a DataFrame. 

1755 matplotlib.axes.Axes.bar : Plot a vertical bar plot using matplotlib. 

1756 

1757 Examples 

1758 -------- 

1759 Basic example 

1760 

1761 .. plot:: 

1762 :context: close-figs 

1763 

1764 >>> df = pd.DataFrame({"lab": ["A", "B", "C"], "val": [10, 30, 20]}) 

1765 >>> ax = df.plot.barh(x="lab", y="val") 

1766 

1767 Plot a whole DataFrame to a horizontal bar plot 

1768 

1769 .. plot:: 

1770 :context: close-figs 

1771 

1772 >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] 

1773 >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] 

1774 >>> index = [ 

1775 ... "snail", 

1776 ... "pig", 

1777 ... "elephant", 

1778 ... "rabbit", 

1779 ... "giraffe", 

1780 ... "coyote", 

1781 ... "horse", 

1782 ... ] 

1783 >>> df = pd.DataFrame({"speed": speed, "lifespan": lifespan}, index=index) 

1784 >>> ax = df.plot.barh() 

1785 

1786 Plot stacked barh charts for the DataFrame 

1787 

1788 .. plot:: 

1789 :context: close-figs 

1790 

1791 >>> ax = df.plot.barh(stacked=True) 

1792 

1793 We can specify colors for each column 

1794 

1795 .. plot:: 

1796 :context: close-figs 

1797 

1798 >>> ax = df.plot.barh(color={"speed": "red", "lifespan": "green"}) 

1799 

1800 Plot a column of the DataFrame to a horizontal bar plot 

1801 

1802 .. plot:: 

1803 :context: close-figs 

1804 

1805 >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] 

1806 >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] 

1807 >>> index = [ 

1808 ... "snail", 

1809 ... "pig", 

1810 ... "elephant", 

1811 ... "rabbit", 

1812 ... "giraffe", 

1813 ... "coyote", 

1814 ... "horse", 

1815 ... ] 

1816 >>> df = pd.DataFrame({"speed": speed, "lifespan": lifespan}, index=index) 

1817 >>> ax = df.plot.barh(y="speed") 

1818 

1819 Plot DataFrame versus the desired column 

1820 

1821 .. plot:: 

1822 :context: close-figs 

1823 

1824 >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] 

1825 >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] 

1826 >>> index = [ 

1827 ... "snail", 

1828 ... "pig", 

1829 ... "elephant", 

1830 ... "rabbit", 

1831 ... "giraffe", 

1832 ... "coyote", 

1833 ... "horse", 

1834 ... ] 

1835 >>> df = pd.DataFrame({"speed": speed, "lifespan": lifespan}, index=index) 

1836 >>> ax = df.plot.barh(x="lifespan") 

1837 """ 

1838 if color is not None: 

1839 kwargs["color"] = color 

1840 return self(kind="barh", x=x, y=y, **kwargs) 

1841 

1842 def box(self, by: IndexLabel | None = None, **kwargs) -> PlotAccessor: 

1843 r""" 

1844 Make a box plot of the DataFrame columns. 

1845 

1846 A box plot is a method for graphically depicting groups of numerical 

1847 data through their quartiles. 

1848 The box extends from the Q1 to Q3 quartile values of the data, 

1849 with a line at the median (Q2). The whiskers extend from the edges 

1850 of box to show the range of the data. The position of the whiskers 

1851 is set by default to 1.5*IQR (IQR = Q3 - Q1) from the edges of the 

1852 box. Outlier points are those past the end of the whiskers. 

1853 

1854 For further details see Wikipedia's 

1855 entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`__. 

1856 

1857 A consideration when using this chart is that the box and the whiskers 

1858 can overlap, which is very common when plotting small sets of data. 

1859 

1860 Parameters 

1861 ---------- 

1862 by : str or sequence 

1863 Column in the DataFrame to group by. 

1864 

1865 **kwargs 

1866 Additional keyword arguments, such as ``ax``, ``figsize``, 

1867 ``title`` and ``grid``, are documented in 

1868 :meth:`DataFrame.plot`. 

1869 

1870 Returns 

1871 ------- 

1872 matplotlib.axes.Axes or Series of them 

1873 A Series of :class:`matplotlib.axes.Axes` is returned when 

1874 ``subplots=True`` or ``by`` is given. 

1875 

1876 See Also 

1877 -------- 

1878 DataFrame.plot : Make plots of a DataFrame. 

1879 DataFrame.boxplot : Another method to draw a box plot. 

1880 Series.plot.box : Draw a box plot from a Series object. 

1881 matplotlib.pyplot.boxplot : Draw a box plot in matplotlib. 

1882 

1883 Examples 

1884 -------- 

1885 Draw a box plot from a DataFrame with four columns of randomly 

1886 generated data. 

1887 

1888 .. plot:: 

1889 :context: close-figs 

1890 

1891 >>> data = np.random.default_rng(42).standard_normal((25, 4)) 

1892 >>> df = pd.DataFrame(data, columns=list("ABCD")) 

1893 >>> ax = df.plot.box() 

1894 

1895 You can also generate groupings if you specify the `by` parameter (which 

1896 can take a column name, or a list or tuple of column names): 

1897 

1898 .. plot:: 

1899 :context: close-figs 

1900 

1901 >>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85] 

1902 >>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list}) 

1903 >>> ax = df.plot.box(column="age", by="gender", figsize=(10, 8)) 

1904 """ 

1905 return self(kind="box", by=by, **kwargs) 

1906 

1907 def hist( 

1908 self, by: IndexLabel | None = None, bins: int = 10, **kwargs 

1909 ) -> PlotAccessor: 

1910 """ 

1911 Make one histogram of the DataFrame's columns. 

1912 

1913 A histogram is a representation of the distribution of data. 

1914 This function groups the values of all given Series in the DataFrame 

1915 into bins and draws all bins in one :class:`matplotlib.axes.Axes`. 

1916 This is useful when the DataFrame's Series are in a similar scale. 

1917 

1918 Parameters 

1919 ---------- 

1920 by : str or sequence, optional 

1921 Column in the DataFrame to group by. 

1922 bins : int, default 10 

1923 Number of histogram bins to be used. 

1924 **kwargs 

1925 Additional keyword arguments, such as ``ax``, ``figsize``, 

1926 ``title`` and ``legend``, are documented in 

1927 :meth:`DataFrame.plot`. 

1928 

1929 Returns 

1930 ------- 

1931 matplotlib.axes.Axes or numpy.ndarray of them 

1932 An ndarray of :class:`matplotlib.axes.Axes` is returned when 

1933 ``subplots=True`` or ``by`` is given. 

1934 

1935 See Also 

1936 -------- 

1937 DataFrame.plot : Make plots of a DataFrame. 

1938 DataFrame.hist : Draw histograms per DataFrame's Series. 

1939 Series.hist : Draw a histogram with Series' data. 

1940 

1941 Examples 

1942 -------- 

1943 When we roll a die 6000 times, we expect to get each value around 1000 

1944 times. But when we roll two dice and sum the result, the distribution 

1945 is going to be quite different. A histogram illustrates those 

1946 distributions. 

1947 

1948 .. plot:: 

1949 :context: close-figs 

1950 

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

1952 >>> df = pd.DataFrame(rng.integers(1, 7, 6000), columns=["one"]) 

1953 >>> df["two"] = df["one"] + rng.integers(1, 7, 6000) 

1954 >>> ax = df.plot.hist(bins=12, alpha=0.5) 

1955 

1956 A grouped histogram can be generated by providing the parameter `by` (which 

1957 can be a column name, or a list of column names): 

1958 

1959 .. plot:: 

1960 :context: close-figs 

1961 

1962 >>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85] 

1963 >>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list}) 

1964 >>> ax = df.plot.hist(column=["age"], by="gender", figsize=(10, 8)) 

1965 """ 

1966 return self(kind="hist", by=by, bins=bins, **kwargs) 

1967 

1968 def kde( 

1969 self, 

1970 bw_method: Literal["scott", "silverman"] 

1971 | float 

1972 | Callable[..., float] 

1973 | None = None, 

1974 ind: np.ndarray | int | None = None, 

1975 weights: np.ndarray | None = None, 

1976 **kwargs, 

1977 ) -> PlotAccessor: 

1978 """ 

1979 Make a Kernel Density Estimate plot using Gaussian kernels. 

1980 

1981 In statistics, `kernel density estimation`_ (KDE) is a non-parametric 

1982 way to estimate the probability density function (PDF) of a random 

1983 variable. This function uses Gaussian kernels and includes automatic 

1984 bandwidth determination. 

1985 

1986 .. _kernel density estimation: 

1987 https://en.wikipedia.org/wiki/Kernel_density_estimation 

1988 

1989 Parameters 

1990 ---------- 

1991 bw_method : str, scalar or callable, optional 

1992 The method used to calculate the estimator bandwidth. This can be 

1993 'scott', 'silverman', a scalar constant or a callable. 

1994 If None (default), 'scott' is used. 

1995 See ``scipy.stats.gaussian_kde`` for more information. 

1996 ind : NumPy array or int, optional 

1997 Evaluation points for the estimated PDF. If None (default), 

1998 1000 equally spaced points are used. If `ind` is a NumPy array, the 

1999 KDE is evaluated at the points passed. If `ind` is an integer, 

2000 `ind` number of equally spaced points are used. 

2001 weights : NumPy array, optional 

2002 Weights of datapoints. This must be the same shape as datapoints. 

2003 If None (default), the samples are assumed to be equally weighted. 

2004 **kwargs 

2005 Additional keyword arguments, such as ``ax``, ``figsize``, 

2006 ``title`` and ``legend``, are documented in 

2007 :meth:`DataFrame.plot`. 

2008 

2009 Returns 

2010 ------- 

2011 matplotlib.axes.Axes or numpy.ndarray of them 

2012 An ndarray of :class:`matplotlib.axes.Axes` is returned when 

2013 ``subplots=True``. 

2014 

2015 See Also 

2016 -------- 

2017 DataFrame.plot : Make plots of a DataFrame. 

2018 scipy.stats.gaussian_kde : Representation of a kernel-density 

2019 estimate using Gaussian kernels. This is the function used 

2020 internally to estimate the PDF. 

2021 

2022 Examples 

2023 -------- 

2024 Given a Series of points randomly sampled from an unknown 

2025 distribution, estimate its PDF using KDE with automatic 

2026 bandwidth determination and plot the results, evaluating them at 

2027 1000 equally spaced points (default): 

2028 

2029 .. plot:: 

2030 :context: close-figs 

2031 

2032 >>> s = pd.Series([1, 2, 2.5, 3, 3.5, 4, 5]) 

2033 >>> ax = s.plot.kde() 

2034 

2035 A scalar bandwidth can be specified. Using a small bandwidth value can 

2036 lead to over-fitting, while using a large bandwidth value may result 

2037 in under-fitting: 

2038 

2039 .. plot:: 

2040 :context: close-figs 

2041 

2042 >>> ax = s.plot.kde(bw_method=0.3) 

2043 

2044 .. plot:: 

2045 :context: close-figs 

2046 

2047 >>> ax = s.plot.kde(bw_method=3) 

2048 

2049 Finally, the `ind` parameter determines the evaluation points for the 

2050 plot of the estimated PDF: 

2051 

2052 .. plot:: 

2053 :context: close-figs 

2054 

2055 >>> ax = s.plot.kde(ind=[1, 2, 3, 4, 5]) 

2056 

2057 For DataFrame, it works in the same way: 

2058 

2059 .. plot:: 

2060 :context: close-figs 

2061 

2062 >>> df = pd.DataFrame( 

2063 ... { 

2064 ... "x": [1, 2, 2.5, 3, 3.5, 4, 5], 

2065 ... "y": [4, 4, 4.5, 5, 5.5, 6, 6], 

2066 ... } 

2067 ... ) 

2068 >>> ax = df.plot.kde() 

2069 

2070 A scalar bandwidth can be specified. Using a small bandwidth value can 

2071 lead to over-fitting, while using a large bandwidth value may result 

2072 in under-fitting: 

2073 

2074 .. plot:: 

2075 :context: close-figs 

2076 

2077 >>> ax = df.plot.kde(bw_method=0.3) 

2078 

2079 .. plot:: 

2080 :context: close-figs 

2081 

2082 >>> ax = df.plot.kde(bw_method=3) 

2083 

2084 Finally, the `ind` parameter determines the evaluation points for the 

2085 plot of the estimated PDF: 

2086 

2087 .. plot:: 

2088 :context: close-figs 

2089 

2090 >>> ax = df.plot.kde(ind=[1, 2, 3, 4, 5, 6]) 

2091 """ 

2092 return self(kind="kde", bw_method=bw_method, ind=ind, weights=weights, **kwargs) 

2093 

2094 density = kde 

2095 

2096 def area( 

2097 self, 

2098 x: Hashable | None = None, 

2099 y: Hashable | None = None, 

2100 stacked: bool = True, 

2101 **kwargs, 

2102 ) -> PlotAccessor: 

2103 """ 

2104 Make a stacked area plot. 

2105 

2106 An area plot displays quantitative data visually. 

2107 This function wraps the matplotlib area function. 

2108 

2109 Parameters 

2110 ---------- 

2111 x : label or position, optional 

2112 Coordinates for the X axis. By default uses the index. 

2113 y : label or position, optional 

2114 Column to plot. By default uses all columns. 

2115 stacked : bool, default True 

2116 Area plots are stacked by default. Set to False to create a 

2117 unstacked plot. 

2118 **kwargs 

2119 Additional keyword arguments, such as ``ax``, ``figsize``, 

2120 ``title`` and ``legend``, are documented in 

2121 :meth:`DataFrame.plot`. 

2122 

2123 Returns 

2124 ------- 

2125 matplotlib.axes.Axes or numpy.ndarray of them 

2126 An ndarray of :class:`matplotlib.axes.Axes` is returned when 

2127 ``subplots=True``. 

2128 

2129 See Also 

2130 -------- 

2131 DataFrame.plot : Make plots of a DataFrame. 

2132 

2133 Examples 

2134 -------- 

2135 Draw an area plot based on basic business metrics: 

2136 

2137 .. plot:: 

2138 :context: close-figs 

2139 

2140 >>> df = pd.DataFrame( 

2141 ... { 

2142 ... "sales": [3, 2, 3, 9, 10, 6], 

2143 ... "signups": [5, 5, 6, 12, 14, 13], 

2144 ... "visits": [20, 42, 28, 62, 81, 50], 

2145 ... }, 

2146 ... index=pd.date_range( 

2147 ... start="2018/01/01", end="2018/07/01", freq="ME" 

2148 ... ), 

2149 ... ) 

2150 >>> ax = df.plot.area() 

2151 

2152 Area plots are stacked by default. To produce an unstacked plot, 

2153 pass ``stacked=False``: 

2154 

2155 .. plot:: 

2156 :context: close-figs 

2157 

2158 >>> ax = df.plot.area(stacked=False) 

2159 

2160 Draw an area plot for a single column: 

2161 

2162 .. plot:: 

2163 :context: close-figs 

2164 

2165 >>> ax = df.plot.area(y="sales") 

2166 

2167 Draw with a different `x`: 

2168 

2169 .. plot:: 

2170 :context: close-figs 

2171 

2172 >>> df = pd.DataFrame( 

2173 ... { 

2174 ... "sales": [3, 2, 3], 

2175 ... "visits": [20, 42, 28], 

2176 ... "day": [1, 2, 3], 

2177 ... } 

2178 ... ) 

2179 >>> ax = df.plot.area(x="day") 

2180 """ 

2181 return self(kind="area", x=x, y=y, stacked=stacked, **kwargs) 

2182 

2183 def pie(self, y: IndexLabel | None = None, **kwargs) -> PlotAccessor: 

2184 """ 

2185 Make a pie plot. 

2186 

2187 A pie plot is a proportional representation of the numerical data in a 

2188 column. This function wraps :meth:`matplotlib.pyplot.pie` for the 

2189 specified column. If no column reference is passed and 

2190 ``subplots=True`` a pie plot is drawn for each numerical column 

2191 independently. 

2192 

2193 Parameters 

2194 ---------- 

2195 y : int or label, optional 

2196 Label or position of the column to plot. 

2197 If not provided, ``subplots=True`` argument must be passed. 

2198 **kwargs 

2199 Additional keyword arguments, such as ``ax``, ``figsize``, 

2200 ``title`` and ``legend``, are documented in 

2201 :meth:`DataFrame.plot`. 

2202 

2203 Returns 

2204 ------- 

2205 matplotlib.axes.Axes or numpy.ndarray of them 

2206 An ndarray of :class:`matplotlib.axes.Axes` is returned when 

2207 ``subplots=True``. 

2208 

2209 See Also 

2210 -------- 

2211 Series.plot.pie : Generate a pie plot for a Series. 

2212 DataFrame.plot : Make plots of a DataFrame. 

2213 

2214 Examples 

2215 -------- 

2216 In the example below we have a DataFrame with the information about 

2217 planet's mass and radius. We pass the 'mass' column to the 

2218 pie function to get a pie plot. 

2219 

2220 .. plot:: 

2221 :context: close-figs 

2222 

2223 >>> df = pd.DataFrame( 

2224 ... {"mass": [0.330, 4.87, 5.97], "radius": [2439.7, 6051.8, 6378.1]}, 

2225 ... index=["Mercury", "Venus", "Earth"], 

2226 ... ) 

2227 >>> plot = df.plot.pie(y="mass", figsize=(5, 5)) 

2228 

2229 .. plot:: 

2230 :context: close-figs 

2231 

2232 >>> plot = df.plot.pie(subplots=True, figsize=(11, 6)) 

2233 """ 

2234 if y is not None: 

2235 kwargs["y"] = y 

2236 if ( 

2237 isinstance(self._parent, ABCDataFrame) 

2238 and kwargs.get("y", None) is None 

2239 and not kwargs.get("subplots", False) 

2240 ): 

2241 raise ValueError("pie requires either y column or 'subplots=True'") 

2242 return self(kind="pie", **kwargs) 

2243 

2244 def scatter( 

2245 self, 

2246 x: Hashable, 

2247 y: Hashable, 

2248 s: Hashable | Sequence[Hashable] | None = None, 

2249 c: Hashable | Sequence[Hashable] | None = None, 

2250 **kwargs, 

2251 ) -> PlotAccessor: 

2252 """ 

2253 Make a scatter plot with varying marker point size and color. 

2254 

2255 The coordinates of each point are defined by two dataframe columns and 

2256 filled circles are used to represent each point. This kind of plot is 

2257 useful to see complex correlations between two variables. Points could 

2258 be for instance natural 2D coordinates like longitude and latitude in 

2259 a map or, in general, any pair of metrics that can be plotted against 

2260 each other. 

2261 

2262 Parameters 

2263 ---------- 

2264 x : int or str 

2265 The column name or column position to be used as horizontal 

2266 coordinates for each point. 

2267 y : int or str 

2268 The column name or column position to be used as vertical 

2269 coordinates for each point. 

2270 s : str, scalar or array-like, optional 

2271 The size of each point. Possible values are: 

2272 

2273 - A string with the name of the column to be used for marker's size. 

2274 

2275 - A single scalar so all points have the same size. 

2276 

2277 - A sequence of scalars, which will be used for each point's size 

2278 recursively. For instance, when passing [2,14] all points size 

2279 will be either 2 or 14, alternatively. 

2280 

2281 c : str, int or array-like, optional 

2282 The color of each point. Possible values are: 

2283 

2284 - A single color string referred to by name, RGB or RGBA code, 

2285 for instance 'red' or '#a98d19'. 

2286 

2287 - A sequence of color strings referred to by name, RGB or RGBA 

2288 code, which will be used for each point's color recursively. For 

2289 instance ['green','yellow'] all points will be filled in green or 

2290 yellow, alternatively. 

2291 

2292 - A column name or position whose values will be used to color the 

2293 marker points according to a colormap. 

2294 

2295 **kwargs 

2296 Additional keyword arguments, such as ``ax``, ``figsize``, 

2297 ``title`` and ``grid``, are documented in 

2298 :meth:`DataFrame.plot`. 

2299 

2300 Returns 

2301 ------- 

2302 matplotlib.axes.Axes or numpy.ndarray of them 

2303 A one-element ndarray is returned when ``subplots=True``. 

2304 

2305 See Also 

2306 -------- 

2307 DataFrame.plot : Make plots of a DataFrame. 

2308 matplotlib.pyplot.scatter : Scatter plot using multiple input data 

2309 formats. 

2310 

2311 Examples 

2312 -------- 

2313 Let's see how to draw a scatter plot using coordinates from the values 

2314 in a DataFrame's columns. 

2315 

2316 .. plot:: 

2317 :context: close-figs 

2318 

2319 >>> df = pd.DataFrame( 

2320 ... [ 

2321 ... [5.1, 3.5, 0], 

2322 ... [4.9, 3.0, 0], 

2323 ... [7.0, 3.2, 1], 

2324 ... [6.4, 3.2, 1], 

2325 ... [5.9, 3.0, 2], 

2326 ... ], 

2327 ... columns=["length", "width", "species"], 

2328 ... ) 

2329 >>> ax1 = df.plot.scatter(x="length", y="width", c="DarkBlue") 

2330 

2331 And now with the color determined by a column as well. 

2332 

2333 .. plot:: 

2334 :context: close-figs 

2335 

2336 >>> ax2 = df.plot.scatter( 

2337 ... x="length", y="width", c="species", colormap="viridis" 

2338 ... ) 

2339 """ 

2340 return self(kind="scatter", x=x, y=y, s=s, c=c, **kwargs) 

2341 

2342 def hexbin( 

2343 self, 

2344 x: Hashable, 

2345 y: Hashable, 

2346 C: Hashable | None = None, 

2347 reduce_C_function: Callable[..., float] | None = None, 

2348 gridsize: int | tuple[int, int] | None = None, 

2349 **kwargs, 

2350 ) -> PlotAccessor: 

2351 """ 

2352 Make a hexagonal binning plot. 

2353 

2354 Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None` 

2355 (the default), this is a histogram of the number of occurrences 

2356 of the observations at ``(x[i], y[i])``. 

2357 

2358 If `C` is specified, specifies values at given coordinates 

2359 ``(x[i], y[i])``. These values are accumulated for each hexagonal 

2360 bin and then reduced according to `reduce_C_function`, 

2361 having as default the NumPy's mean function (:meth:`numpy.mean`). 

2362 (If `C` is specified, it must also be a 1-D sequence 

2363 of the same length as `x` and `y`, or a column label.) 

2364 

2365 Parameters 

2366 ---------- 

2367 x : int or str 

2368 The column label or position for x points. 

2369 y : int or str 

2370 The column label or position for y points. 

2371 C : int or str, optional 

2372 The column label or position for the value of `(x, y)` point. 

2373 reduce_C_function : callable, default `np.mean` 

2374 Function of one argument that reduces all the values in a bin to 

2375 a single number (e.g. `np.mean`, `np.max`, `np.sum`, `np.std`). 

2376 gridsize : int or tuple of (int, int), default 100 

2377 The number of hexagons in the x-direction. 

2378 The corresponding number of hexagons in the y-direction is 

2379 chosen in a way that the hexagons are approximately regular. 

2380 Alternatively, gridsize can be a tuple with two elements 

2381 specifying the number of hexagons in the x-direction and the 

2382 y-direction. 

2383 The hexagons tile only the extent of the data, so for a fixed 

2384 gridsize their apparent size varies with the range of the data 

2385 and the axis limits. To control the area covered by the 

2386 hexagons, pass matplotlib's ``extent`` keyword via ``**kwargs``. 

2387 **kwargs 

2388 Additional keyword arguments, such as ``ax``, ``figsize``, 

2389 ``title`` and ``grid``, are documented in 

2390 :meth:`DataFrame.plot`. 

2391 

2392 Returns 

2393 ------- 

2394 matplotlib.axes.Axes or numpy.ndarray of them 

2395 A one-element ndarray is returned when ``subplots=True``. 

2396 

2397 See Also 

2398 -------- 

2399 DataFrame.plot : Make plots of a DataFrame. 

2400 matplotlib.pyplot.hexbin : Hexagonal binning plot using matplotlib, 

2401 the matplotlib function that is used under the hood. 

2402 

2403 Examples 

2404 -------- 

2405 The following examples are generated with random data from 

2406 a normal distribution. 

2407 

2408 .. plot:: 

2409 :context: close-figs 

2410 

2411 >>> n = 10000 

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

2413 >>> df = pd.DataFrame( 

2414 ... {"x": rng.standard_normal(n), "y": rng.standard_normal(n)} 

2415 ... ) 

2416 >>> ax = df.plot.hexbin(x="x", y="y", gridsize=20) 

2417 

2418 The next example uses `C` and `np.sum` as `reduce_C_function`. 

2419 Note that `'observations'` values ranges from 1 to 5 but the result 

2420 plot shows values up to more than 25. This is because of the 

2421 `reduce_C_function`. 

2422 

2423 .. plot:: 

2424 :context: close-figs 

2425 

2426 >>> n = 500 

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

2428 >>> df = pd.DataFrame( 

2429 ... { 

2430 ... "coord_x": rng.uniform(-3, 3, size=n), 

2431 ... "coord_y": rng.uniform(30, 50, size=n), 

2432 ... "observations": rng.integers(1, 5, size=n), 

2433 ... } 

2434 ... ) 

2435 >>> ax = df.plot.hexbin( 

2436 ... x="coord_x", 

2437 ... y="coord_y", 

2438 ... C="observations", 

2439 ... reduce_C_function=np.sum, 

2440 ... gridsize=10, 

2441 ... cmap="viridis", 

2442 ... ) 

2443 """ 

2444 if reduce_C_function is not None: 

2445 kwargs["reduce_C_function"] = reduce_C_function 

2446 if gridsize is not None: 

2447 kwargs["gridsize"] = gridsize 

2448 

2449 return self(kind="hexbin", x=x, y=y, C=C, **kwargs) 

2450 

2451 

2452_backends: dict[str, types.ModuleType] = {} 

2453 

2454 

2455def _load_backend(backend: str) -> types.ModuleType: 

2456 """ 

2457 Load a pandas plotting backend. 

2458 

2459 Parameters 

2460 ---------- 

2461 backend : str 

2462 The identifier for the backend. Either an entrypoint item registered 

2463 with importlib.metadata, "matplotlib", or a module name. 

2464 

2465 Returns 

2466 ------- 

2467 types.ModuleType 

2468 The imported backend. 

2469 """ 

2470 from importlib.metadata import entry_points 

2471 

2472 if backend == "matplotlib": 

2473 # Because matplotlib is an optional dependency and first-party backend, 

2474 # we need to attempt an import here to raise an ImportError if needed. 

2475 try: 

2476 module = importlib.import_module("pandas.plotting._matplotlib") 

2477 except ImportError: 

2478 raise ImportError( 

2479 "matplotlib is required for plotting when the " 

2480 'default backend "matplotlib" is selected.' 

2481 ) from None 

2482 return module 

2483 

2484 found_backend = False 

2485 

2486 eps = entry_points() 

2487 key = "pandas_plotting_backends" 

2488 # entry_points lost dict API ~ PY 3.10 

2489 # https://github.com/python/importlib_metadata/issues/298 

2490 if hasattr(eps, "select"): 

2491 entry = eps.select(group=key) 

2492 else: 

2493 entry = eps.get(key, ()) # type: ignore[attr-defined] 

2494 for entry_point in entry: 

2495 found_backend = entry_point.name == backend 

2496 if found_backend: 

2497 module = entry_point.load() 

2498 break 

2499 

2500 if not found_backend: 

2501 # Fall back to unregistered, module name approach. 

2502 try: 

2503 module = importlib.import_module(backend) 

2504 found_backend = True 

2505 except ImportError: 

2506 # We re-raise later on. 

2507 pass 

2508 

2509 if found_backend: 

2510 if hasattr(module, "plot"): 

2511 # Validate that the interface is implemented when the option is set, 

2512 # rather than at plot time. 

2513 return module 

2514 

2515 raise ValueError( 

2516 f"Could not find plotting backend '{backend}'. Ensure that you've " 

2517 f"installed the package providing the '{backend}' entrypoint, or that " 

2518 "the package has a top-level `.plot` method." 

2519 ) 

2520 

2521 

2522def _get_plot_backend(backend: str | None = None): 

2523 """ 

2524 Return the plotting backend to use (e.g. `pandas.plotting._matplotlib`). 

2525 

2526 The plotting system of pandas uses matplotlib by default, but the idea here 

2527 is that it can also work with other third-party backends. This function 

2528 returns the module which provides a top-level `.plot` method that will 

2529 actually do the plotting. The backend is specified from a string, which 

2530 either comes from the keyword argument `backend`, or, if not specified, from 

2531 the option `pandas.options.plotting.backend`. All the rest of the code in 

2532 this file uses the backend specified there for the plotting. 

2533 

2534 The backend is imported lazily, as matplotlib is a soft dependency, and 

2535 pandas can be used without it being installed. 

2536 

2537 Notes 

2538 ----- 

2539 Modifies `_backends` with imported backend as a side effect. 

2540 """ 

2541 backend_str: str = backend or config["plotting"]["backend"] 

2542 

2543 if backend_str in _backends: 

2544 return _backends[backend_str] 

2545 

2546 module = _load_backend(backend_str) 

2547 _backends[backend_str] = module 

2548 return module