Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Use a dataclass instead of a dict as a return type for boxplot()#27788

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
timhoffm wants to merge1 commit intomatplotlib:main
base:main
Choose a base branch
Loading
fromtimhoffm:return-dataclass
Draft
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletionsdoc/api/next_api_changes/behavior/27788-TH.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
``boxplot()`` returns a dataclass instead of a dict
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The dataclass still supports dict-like access for backwards compatibility.
2 changes: 1 addition & 1 deletiongalleries/examples/statistics/boxplot_color.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,7 +29,7 @@
labels=labels) # will be used to label x-ticks

# fill with colors
for patch, color in zip(bplot['boxes'], colors):
for patch, color in zip(bplot.boxes, colors):
patch.set_facecolor(color)

plt.show()
Expand Down
10 changes: 5 additions & 5 deletionsgalleries/examples/statistics/boxplot_demo.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,9 +108,9 @@
fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)

bp = ax1.boxplot(data, notch=False, sym='+', vert=True, whis=1.5)
plt.setp(bp['boxes'], color='black')
plt.setp(bp['whiskers'], color='black')
plt.setp(bp['fliers'], color='red', marker='+')
plt.setp(bp.boxes, color='black')
plt.setp(bp.whiskers, color='black')
plt.setp(bp.fliers, color='red', marker='+')

# Add a horizontal grid to the plot, but make it very light in color
# so we can use it for reading data values but not be distracting
Expand DownExpand Up@@ -229,8 +229,8 @@ def fake_bootstrapper(n):

ax.set_xlabel('treatment')
ax.set_ylabel('response')
plt.setp(bp['whiskers'], color='k', linestyle='-')
plt.setp(bp['fliers'], markersize=3.0)
plt.setp(bp.whiskers, color='k', linestyle='-')
plt.setp(bp.fliers, markersize=3.0)
plt.show()


Expand Down
30 changes: 20 additions & 10 deletionslib/matplotlib/axes/_axes.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3908,10 +3908,10 @@ def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,

Returns
-------
dict
Adictionary mapping each component of the boxplot to a list
of the `.Line2D` instances created.That dictionary has the
followingkeys (assuming vertical boxplots):
BoxplotArtists
Adataclass mapping each component of the boxplot to a list
of the `.Line2D` instances created.The dataclass has the
followingattributes (assuming vertical boxplots):

- ``boxes``: the main body of the boxplot showing the
quartiles and the median's confidence intervals if
Expand All@@ -3930,6 +3930,10 @@ def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,

- ``means``: points or lines representing the means.

.. versionchanged:: 3.9
Formerly, a dict was returned. The return value is now a dataclass, that
still supports dict-like access for backward-compatibility.

Other Parameters
----------------
showcaps : bool, default: :rc:`boxplot.showcaps`
Expand DownExpand Up@@ -4171,10 +4175,10 @@ def bxp(self, bxpstats, positions=None, widths=None, vert=True,

Returns
-------
dict
Adictionary mapping each component of the boxplot to a list
of the `.Line2D` instances created.That dictionary has the
followingkeys (assuming vertical boxplots):
BoxplotArtists
Adataclass mapping each component of the boxplot to a list
of the `.Line2D` instances created.The dataclass has the
followingattributes (assuming vertical boxplots):

- ``boxes``: main bodies of the boxplot showing the quartiles, and
the median's confidence intervals if enabled.
Expand All@@ -4184,6 +4188,10 @@ def bxp(self, bxpstats, positions=None, widths=None, vert=True,
- ``fliers``: points representing data beyond the whiskers (fliers).
- ``means``: points or lines representing the means.

.. versionchanged:: 3.9
Formerly, a dict was returned. The return value is now a dataclass, that
still supports dict-like access for backward-compatibility.

See Also
--------
boxplot : Draw a boxplot from data instead of pre-computed statistics.
Expand DownExpand Up@@ -4390,8 +4398,10 @@ def do_patch(xs, ys, **kwargs):

self._request_autoscale_view()

return dict(whiskers=whiskers, caps=caps, boxes=boxes,
medians=medians, fliers=fliers, means=means)
return cbook.BoxplotArtists(
whiskers=whiskers, caps=caps, boxes=boxes,
medians=medians, fliers=fliers, means=means
)

@staticmethod
def _parse_scatter_color_args(c, edgecolors, kwargs, xsize,
Expand Down
28 changes: 28 additions & 0 deletionslib/matplotlib/cbook.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import collections
import collections.abc
import contextlib
import dataclasses
import functools
import gzip
import itertools
Expand All@@ -19,6 +20,7 @@
import time
import traceback
import types
from typing import Union
import weakref

import numpy as np
Expand DownExpand Up@@ -1126,6 +1128,32 @@ def _broadcast_with_masks(*args, compress=False):
return inputs


@dataclasses.dataclass(frozen=True)
class BoxplotArtists(collections.abc.Mapping):
"""
Collection of the artists created by `~.Axes.boxplot`.

For backward compatibility with the previously used dict representation,
this can alternatively be accessed like a (read-only) dict. However,
dict-like access is discouraged.
"""
boxes: Union[list["matplotlib.lines.Line2D"], list["matplotlib.patches.Patch"]]
medians: list["matplotlib.lines.Line2D"]
whiskers: list["matplotlib.lines.Line2D"]
caps: list["matplotlib.lines.Line2D"]
fliers: list["matplotlib.lines.Line2D"]
means: list["matplotlib.lines.Line2D"]

def __getitem__(self, key):
return getattr(self, key)

def __iter__(self):
return iter(self.__annotations__)

def __len__(self):
return len(self.__annotations__)


def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None,
autorange=False):
r"""
Expand Down
17 changes: 17 additions & 0 deletionslib/matplotlib/cbook.pyi
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
import collections.abc
from collections.abc import Callable, Collection, Generator, Iterable, Iterator
import contextlib
import dataclasses
import os
from pathlib import Path

from matplotlib.artist import Artist
from matplotlib.lines import Line2D
from matplotlib.patches import Patch

import numpy as np
from numpy.typing import ArrayLike
Expand All@@ -15,6 +18,7 @@ from typing import (
IO,
Literal,
TypeVar,
Union,
overload,
)

Expand DownExpand Up@@ -131,6 +135,19 @@ class GrouperView(Generic[_T]):
def simple_linear_interpolation(a: ArrayLike, steps: int) -> np.ndarray: ...
def delete_masked_points(*args): ...
def _broadcast_with_masks(*args: ArrayLike, compress: bool = ...) -> list[ArrayLike]: ...

@dataclasses.dataclass
class BoxplotArtists(collections.abc.Mapping):
boxes: Union[list[Line2D], list[Patch]]
medians: list[Line2D]
whiskers: list[Line2D]
caps: list[Line2D]
fliers: list[Line2D]
means: list[Line2D]
def __getitem__(self, key: str) -> Union[list[Line2D], list[Patch]]: ...
def __iter__(self) -> Iterator[str]: ...
def __len__(self) -> int: ...

def boxplot_stats(
X: ArrayLike,
whis: float | tuple[float, float] = ...,
Expand Down
9 changes: 9 additions & 0 deletionslib/matplotlib/tests/test_axes.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3645,6 +3645,15 @@ def test_boxplot_mod_artist_after_plotting():
obj.set_color('green')


def test_boxplot_return_dict_and_dataclass():
# check that the returned BoxplotArtists works as a dataclass and as a dict
# i.e. bp['key'] and bp.key are equivalent
fig, ax = plt.subplots()
bp = ax.boxplot(np.linspace(0, 1, 11), sym="o")
for key in bp:
assert bp[key] is getattr(bp, key)


@image_comparison(['violinplot_vert_baseline.png',
'violinplot_vert_baseline.png'])
def test_vert_violinplot_baseline():
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp