Skip to content

TST: fix warnings on multiple subplots #37274

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 6 commits into from
Nov 9, 2020
Merged
Show file tree
Hide file tree
Changes from 5 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
54 changes: 36 additions & 18 deletions pandas/tests/plotting/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,41 +550,59 @@ def _unpack_cycler(self, rcParams, field="color"):
return [v[field] for v in rcParams["axes.prop_cycle"]]


def _check_plot_works(f, filterwarnings="always", **kwargs):
def _check_plot_works(f, filterwarnings="always", default_axes=False, **kwargs):
"""
Create plot and ensure that plot return object is valid.
"""
import matplotlib.pyplot as plt

if default_axes:
gen_plots = _gen_default_plot
else:
gen_plots = _gen_two_subplots

ret = None
with warnings.catch_warnings():
warnings.simplefilter(filterwarnings)
try:
try:
fig = kwargs["figure"]
except KeyError:
fig = plt.gcf()

fig = kwargs.get("figure", plt.gcf())
plt.clf()

kwargs.get("ax", fig.add_subplot(211))
ret = f(**kwargs)

tm.assert_is_valid_plot_return_object(ret)

if f is pd.plotting.bootstrap_plot:
assert "ax" not in kwargs
else:
kwargs["ax"] = fig.add_subplot(212)

ret = f(**kwargs)
tm.assert_is_valid_plot_return_object(ret)
for ret in gen_plots(f, fig, **kwargs):
tm.assert_is_valid_plot_return_object(ret)

with tm.ensure_clean(return_filelike=True) as path:
plt.savefig(path)

except Exception as err:
raise err
finally:
tm.close(fig)

return ret


def _gen_default_plot(f, fig, **kwargs):
"""
Create plot in a default way.
"""
yield f(**kwargs)
Comment on lines +611 to +615
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here fig is a dummy variable.
We have it here to ensure the same function signature with _get_two_subplots.

Alternatively, we can create empty figure in both generator functions and yield fig, f(**kwargs).

It seemed to me that yielding one argument rather than two is clearer, thus I did it the way it is now.



def _gen_two_subplots(f, fig, **kwargs):
"""
Create plot on two subplots forcefully created.
"""
kwargs.get("ax", fig.add_subplot(211))
yield f(**kwargs)

if f is pd.plotting.bootstrap_plot:
assert "ax" not in kwargs
else:
kwargs["ax"] = fig.add_subplot(212)
yield f(**kwargs)


def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))
return pth
27 changes: 22 additions & 5 deletions pandas/tests/plotting/test_hist_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ def test_hist_with_legend(self, by, expected_axes_num, expected_layout):
s = Series(np.random.randn(30), index=index, name="a")
s.index.name = "b"

axes = _check_plot_works(s.hist, legend=True, by=by)
# Use default_axes=True when plotting method generate subplots itself
axes = _check_plot_works(s.hist, default_axes=True, legend=True, by=by)
self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout)
self._check_legend_labels(axes, "a")

Expand Down Expand Up @@ -332,7 +333,8 @@ def test_tight_layout(self):
dtype=np.int64,
)
)
_check_plot_works(df.hist)
# Use default_axes=True when plotting method generate subplots itself
_check_plot_works(df.hist, default_axes=True)
self.plt.tight_layout()

tm.close()
Expand All @@ -345,8 +347,10 @@ def test_hist_subplot_xrot(self):
"animal": ["pig", "rabbit", "pig", "pig", "rabbit"],
}
)
# Use default_axes=True when plotting method generate subplots itself
axes = _check_plot_works(
df.hist,
default_axes=True,
filterwarnings="always",
column="length",
by="animal",
Expand Down Expand Up @@ -374,9 +378,14 @@ def test_hist_column_order_unchanged(self, column, expected):
index=["pig", "rabbit", "duck", "chicken", "horse"],
)

axes = _check_plot_works(df.hist, column=column, layout=(1, 3))
# Use default_axes=True when plotting method generate subplots itself
axes = _check_plot_works(
df.hist,
default_axes=True,
column=column,
layout=(1, 3),
)
result = [axes[0, i].get_title() for i in range(3)]

assert result == expected

@pytest.mark.parametrize(
Expand Down Expand Up @@ -407,7 +416,15 @@ def test_hist_with_legend(self, by, column):
index = Index(15 * ["1"] + 15 * ["2"], name="c")
df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"])

axes = _check_plot_works(df.hist, legend=True, by=by, column=column)
# Use default_axes=True when plotting method generate subplots itself
axes = _check_plot_works(
df.hist,
default_axes=True,
legend=True,
by=by,
column=column,
)

self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout)
if by is None and column is None:
axes = axes[0]
Expand Down