Skip to content

BUG df.plot.box handles matplotlib Axes with sharey=True #54940

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ Period

Plotting
^^^^^^^^
-
- Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`)
-

Groupby/resample/rolling
Expand Down
45 changes: 27 additions & 18 deletions pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@
from pandas._typing import MatplotlibColor


def _set_ticklabels(ax: Axes, labels: list[str], is_vertical: bool, **kwargs) -> None:
"""Set the tick labels of a given axis.

Due to https://github.com/matplotlib/matplotlib/pull/17266, we need to handle the
case of repeated ticks (due to `FixedLocator`) and thus we duplicate the number of
labels.
"""
ticks = ax.get_xticks() if is_vertical else ax.get_yticks()
if len(ticks) != len(labels):
i, remainder = divmod(len(ticks), len(labels))
assert remainder == 0, remainder
labels *= i
if is_vertical:
ax.set_xticklabels(labels, **kwargs)
else:
ax.set_yticklabels(labels, **kwargs)


class BoxPlot(LinePlot):
@property
def _kind(self) -> Literal["box"]:
Expand Down Expand Up @@ -193,7 +211,9 @@ def _make_plot(self) -> None:
)
self.maybe_color_bp(bp)
self._return_obj[label] = ret
self._set_ticklabels(ax, ticklabels)
_set_ticklabels(
ax=ax, labels=ticklabels, is_vertical=self.orientation == "vertical"
)
else:
y = self.data.values.T
ax = self._get_ax(0)
Expand All @@ -209,13 +229,9 @@ def _make_plot(self) -> None:
labels = [pprint_thing(left) for left in labels]
if not self.use_index:
labels = [pprint_thing(key) for key in range(len(labels))]
self._set_ticklabels(ax, labels)

def _set_ticklabels(self, ax: Axes, labels: list[str]) -> None:
if self.orientation == "vertical":
ax.set_xticklabels(labels)
else:
ax.set_yticklabels(labels)
_set_ticklabels(
ax=ax, labels=labels, is_vertical=self.orientation == "vertical"
)

def _make_legend(self) -> None:
pass
Expand Down Expand Up @@ -382,16 +398,9 @@ def plot_group(keys, values, ax: Axes, **kwds):
ax.tick_params(axis="both", labelsize=fontsize)

# GH 45465: x/y are flipped when "vert" changes
is_vertical = kwds.get("vert", True)
ticks = ax.get_xticks() if is_vertical else ax.get_yticks()
if len(ticks) != len(keys):
i, remainder = divmod(len(ticks), len(keys))
assert remainder == 0, remainder
keys *= i
if is_vertical:
ax.set_xticklabels(keys, rotation=rot)
else:
ax.set_yticklabels(keys, rotation=rot)
_set_ticklabels(
ax=ax, labels=keys, is_vertical=kwds.get("vert", True), rotation=rot
)
maybe_color_bp(bp, **kwds)

# Return axes in multiplot case, maybe revisit later # 985
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/plotting/test_boxplot_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,22 @@ def test_plot_xlabel_ylabel(self, vert):
assert ax.get_xlabel() == xlabel
assert ax.get_ylabel() == ylabel

@pytest.mark.parametrize("vert", [True, False])
def test_plot_box(self, vert):
# GH 54941
rng = np.random.default_rng(2)
df1 = DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list("ABCD"))
df2 = DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list("ABCD"))

xlabel, ylabel = "x", "y"
_, axs = plt.subplots(ncols=2, figsize=(10, 7), sharey=True)
df1.plot.box(ax=axs[0], vert=vert, xlabel=xlabel, ylabel=ylabel)
df2.plot.box(ax=axs[1], vert=vert, xlabel=xlabel, ylabel=ylabel)
for ax in axs:
assert ax.get_xlabel() == xlabel
assert ax.get_ylabel() == ylabel
mpl.pyplot.close()

@pytest.mark.parametrize("vert", [True, False])
def test_boxplot_xlabel_ylabel(self, vert):
df = DataFrame(
Expand Down