Skip to content

[BUG] Fix DataFrameGroupBy.boxplot with subplots=False fails for object columns #44003

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 8 commits into from
Nov 14, 2021
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ Period

Plotting
^^^^^^^^
-
- When given non-numeric data, :meth:`DataFrame.boxplot` now raises a ``ValueError`` rather than a cryptic ``KeyError`` or ``ZeroDivsionError``, in line with other plotting functions like :meth:`DataFrame.hist`. (:issue:`43480`)
-

Groupby/resample/rolling
Expand Down
5 changes: 5 additions & 0 deletions pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,11 @@ def plot_group(keys, values, ax: Axes):
with plt.rc_context(rc):
ax = plt.gca()
data = data._get_numeric_data()
naxes = len(data.columns)
if naxes == 0:
raise ValueError(
"boxplot method requires numerical columns, nothing to plot."
)
if columns is None:
columns = data.columns
else:
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/plotting/test_boxplot_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,14 @@ def test_groupby_boxplot_subplots_false(self, col, expected_xticklabel):
result_xticklabel = [x.get_text() for x in axes.get_xticklabels()]
assert expected_xticklabel == result_xticklabel

def test_groupby_boxplot_object(self):
# GH 43480
df = self.hist_df.astype("object")
grouped = df.groupby("gender")
msg = "boxplot method requires numerical columns, nothing to plot"
with pytest.raises(ValueError, match=msg):
_check_plot_works(grouped.boxplot, subplots=False)

def test_boxplot_multiindex_column(self):
# GH 16748
arrays = [
Expand Down