Skip to content

Commit 670d384

Browse files
thetestspecimenpmhatre1
authored andcommitted
BUG: Fix error for boxplot when using a pre-grouped DataFrame with more than one grouping (pandas-dev#57985)
1 parent 44eff04 commit 670d384

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

doc/source/whatsnew/v3.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ Period
399399

400400
Plotting
401401
^^^^^^^^
402-
-
402+
- Bug in :meth:`.DataFrameGroupBy.boxplot` failed when there were multiple groupings (:issue:`14701`)
403403
-
404404

405405
Groupby/resample/rolling

pandas/plotting/_matplotlib/boxplot.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -533,14 +533,14 @@ def boxplot_frame_groupby(
533533
)
534534
axes = flatten_axes(axes)
535535

536-
ret = pd.Series(dtype=object)
537-
536+
data = {}
538537
for (key, group), ax in zip(grouped, axes):
539538
d = group.boxplot(
540539
ax=ax, column=column, fontsize=fontsize, rot=rot, grid=grid, **kwds
541540
)
542541
ax.set_title(pprint_thing(key))
543-
ret.loc[key] = d
542+
data[key] = d
543+
ret = pd.Series(data)
544544
maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
545545
else:
546546
keys, frames = zip(*grouped)

pandas/tests/plotting/test_boxplot_method.py

+14
Original file line numberDiff line numberDiff line change
@@ -740,3 +740,17 @@ def test_boxplot_multiindex_column(self):
740740
expected_xticklabel = ["(bar, one)", "(bar, two)"]
741741
result_xticklabel = [x.get_text() for x in axes.get_xticklabels()]
742742
assert expected_xticklabel == result_xticklabel
743+
744+
@pytest.mark.parametrize("group", ["X", ["X", "Y"]])
745+
def test_boxplot_multi_groupby_groups(self, group):
746+
# GH 14701
747+
rows = 20
748+
df = DataFrame(
749+
np.random.default_rng(12).normal(size=(rows, 2)), columns=["Col1", "Col2"]
750+
)
751+
df["X"] = Series(np.repeat(["A", "B"], int(rows / 2)))
752+
df["Y"] = Series(np.tile(["C", "D"], int(rows / 2)))
753+
grouped = df.groupby(group)
754+
_check_plot_works(df.boxplot, by=group, default_axes=True)
755+
_check_plot_works(df.plot.box, by=group, default_axes=True)
756+
_check_plot_works(grouped.boxplot, default_axes=True)

0 commit comments

Comments
 (0)