Skip to content

TST: Clean plotting tests #53917

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 2 commits into from
Jun 29, 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
108 changes: 80 additions & 28 deletions pandas/tests/plotting/test_boxplot_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@
mpl = pytest.importorskip("matplotlib")


def _check_ax_limits(col, ax):
y_min, y_max = ax.get_ylim()
assert y_min <= col.min()
assert y_max >= col.max()


class TestDataFramePlots:
def test_stacked_boxplot_set_axis(self):
# GH2980
Expand Down Expand Up @@ -88,18 +94,30 @@ def test_boxplot_legacy2(self):
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
_check_plot_works(df.boxplot, by="X")

def test_boxplot_legacy2_with_ax(self):
df = DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
df["Y"] = Series(["A"] * 10)
# When ax is supplied and required number of axes is 1,
# passed ax should be used:
fig, ax = mpl.pyplot.subplots()
_, ax = mpl.pyplot.subplots()
axes = df.boxplot("Col1", by="X", ax=ax)
ax_axes = ax.axes
assert ax_axes is axes

def test_boxplot_legacy2_with_ax_return_type(self):
df = DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
df["Y"] = Series(["A"] * 10)
fig, ax = mpl.pyplot.subplots()
axes = df.groupby("Y").boxplot(ax=ax, return_type="axes")
ax_axes = ax.axes
assert ax_axes is axes["A"]

def test_boxplot_legacy2_with_multi_col(self):
df = DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
df["Y"] = Series(["A"] * 10)
# Multiple columns with an ax argument should use same figure
fig, ax = mpl.pyplot.subplots()
with tm.assert_produces_warning(UserWarning):
Expand All @@ -108,9 +126,13 @@ def test_boxplot_legacy2(self):
)
assert axes["Col1"].get_figure() is fig

def test_boxplot_legacy2_by_none(self):
df = DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
df["Y"] = Series(["A"] * 10)
# When by is None, check that all relevant lines are present in the
# dict
fig, ax = mpl.pyplot.subplots()
_, ax = mpl.pyplot.subplots()
d = df.boxplot(ax=ax, return_type="dict")
lines = list(itertools.chain.from_iterable(d.values()))
assert len(ax.get_lines()) == len(lines)
Expand All @@ -135,24 +157,20 @@ def test_boxplot_return_type_legacy(self):
result = df.boxplot()
_check_box_return_type(result, "axes")

with tm.assert_produces_warning(False):
result = df.boxplot(return_type="dict")
_check_box_return_type(result, "dict")

with tm.assert_produces_warning(False):
result = df.boxplot(return_type="axes")
_check_box_return_type(result, "axes")
@pytest.mark.parametrize("return_type", ["dict", "axes", "both"])
def test_boxplot_return_type_legacy_return_type(self, return_type):
# API change in https://github.com/pandas-dev/pandas/pull/7096

df = DataFrame(
np.random.randn(6, 4),
index=list(string.ascii_letters[:6]),
columns=["one", "two", "three", "four"],
)
with tm.assert_produces_warning(False):
result = df.boxplot(return_type="both")
_check_box_return_type(result, "both")
result = df.boxplot(return_type=return_type)
_check_box_return_type(result, return_type)

def test_boxplot_axis_limits(self, hist_df):
def _check_ax_limits(col, ax):
y_min, y_max = ax.get_ylim()
assert y_min <= col.min()
assert y_max >= col.max()

df = hist_df.copy()
df["age"] = np.random.randint(1, 20, df.shape[0])
# One full row
Expand All @@ -161,6 +179,9 @@ def _check_ax_limits(col, ax):
_check_ax_limits(df["weight"], weight_ax)
assert weight_ax._sharey == height_ax

def test_boxplot_axis_limits_two_rows(self, hist_df):
df = hist_df.copy()
df["age"] = np.random.randint(1, 20, df.shape[0])
# Two rows, one partial
p = df.boxplot(["height", "weight", "age"], by="category")
height_ax, weight_ax, age_ax = p[0, 0], p[0, 1], p[1, 0]
Expand Down Expand Up @@ -275,7 +296,7 @@ def test_color_kwd_errors(self, dict_colors, msg):
)
def test_specified_props_kwd(self, props, expected):
# GH 30346
df = DataFrame({k: np.random.random(100) for k in "ABC"})
df = DataFrame({k: np.random.random(10) for k in "ABC"})
kwd = {props: {"color": "C1"}}
result = df.boxplot(return_type="dict", **kwd)

Expand All @@ -285,9 +306,9 @@ def test_specified_props_kwd(self, props, expected):
def test_plot_xlabel_ylabel(self, vert):
df = DataFrame(
{
"a": np.random.randn(100),
"b": np.random.randn(100),
"group": np.random.choice(["group1", "group2"], 100),
"a": np.random.randn(10),
"b": np.random.randn(10),
"group": np.random.choice(["group1", "group2"], 10),
}
)
xlabel, ylabel = "x", "y"
Expand All @@ -299,9 +320,9 @@ def test_plot_xlabel_ylabel(self, vert):
def test_boxplot_xlabel_ylabel(self, vert):
df = DataFrame(
{
"a": np.random.randn(100),
"b": np.random.randn(100),
"group": np.random.choice(["group1", "group2"], 100),
"a": np.random.randn(10),
"b": np.random.randn(10),
"group": np.random.choice(["group1", "group2"], 10),
}
)
xlabel, ylabel = "x", "y"
Expand All @@ -313,9 +334,9 @@ def test_boxplot_xlabel_ylabel(self, vert):
def test_boxplot_group_xlabel_ylabel(self, vert):
df = DataFrame(
{
"a": np.random.randn(100),
"b": np.random.randn(100),
"group": np.random.choice(["group1", "group2"], 100),
"a": np.random.randn(10),
"b": np.random.randn(10),
"group": np.random.choice(["group1", "group2"], 10),
}
)
xlabel, ylabel = "x", "y"
Expand All @@ -325,6 +346,15 @@ def test_boxplot_group_xlabel_ylabel(self, vert):
assert subplot.get_ylabel() == ylabel
mpl.pyplot.close()

@pytest.mark.parametrize("vert", [True, False])
def test_boxplot_group_no_xlabel_ylabel(self, vert):
df = DataFrame(
{
"a": np.random.randn(10),
"b": np.random.randn(10),
"group": np.random.choice(["group1", "group2"], 10),
}
)
ax = df.boxplot(by="group", vert=vert)
for subplot in ax:
target_label = subplot.get_xlabel() if vert else subplot.get_ylabel()
Expand All @@ -338,6 +368,9 @@ def test_boxplot_legacy1(self, hist_df):
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
axes = _check_plot_works(grouped.boxplot, return_type="axes")
_check_axes_shape(list(axes.values), axes_num=2, layout=(1, 2))

def test_boxplot_legacy1_return_type(self, hist_df):
grouped = hist_df.groupby(by="gender")
axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes")
_check_axes_shape(axes, axes_num=1, layout=(1, 1))

Expand All @@ -350,6 +383,11 @@ def test_boxplot_legacy2(self):
axes = _check_plot_works(grouped.boxplot, return_type="axes")
_check_axes_shape(list(axes.values), axes_num=10, layout=(4, 3))

@pytest.mark.slow
def test_boxplot_legacy2_return_type(self):
tuples = zip(string.ascii_letters[:10], range(10))
df = DataFrame(np.random.rand(10, 3), index=MultiIndex.from_tuples(tuples))
grouped = df.groupby(level=1)
axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes")
_check_axes_shape(axes, axes_num=1, layout=(1, 1))

Expand Down Expand Up @@ -387,8 +425,14 @@ def test_grouped_plot_fignums(self):
assert len(res) == 2
tm.close()

def test_grouped_plot_fignums_excluded_col(self):
n = 10
weight = Series(np.random.normal(166, 20, size=n))
height = Series(np.random.normal(60, 10, size=n))
gender = np.random.RandomState(42).choice(["male", "female"], size=n)
df = DataFrame({"height": height, "weight": weight, "gender": gender})
# now works with GH 5610 as gender is excluded
res = df.groupby("gender").hist()
df.groupby("gender").hist()
tm.close()

@pytest.mark.slow
Expand Down Expand Up @@ -545,10 +589,14 @@ def test_grouped_box_multiple_axes(self, hist_df):
# location should be changed if other test is added
# which has earlier alphabetical order
with tm.assert_produces_warning(UserWarning):
fig, axes = mpl.pyplot.subplots(2, 2)
_, axes = mpl.pyplot.subplots(2, 2)
df.groupby("category").boxplot(column="height", return_type="axes", ax=axes)
_check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(2, 2))

@pytest.mark.slow
def test_grouped_box_multiple_axes_on_fig(self, hist_df):
# GH 6970, GH 7069
df = hist_df
fig, axes = mpl.pyplot.subplots(2, 3)
with tm.assert_produces_warning(UserWarning):
returned = df.boxplot(
Expand All @@ -572,6 +620,10 @@ def test_grouped_box_multiple_axes(self, hist_df):
tm.assert_numpy_array_equal(returned, axes[1])
assert returned[0].figure is fig

@pytest.mark.slow
def test_grouped_box_multiple_axes_ax_error(self, hist_df):
# GH 6970, GH 7069
df = hist_df
msg = "The number of passed axes must be 3, the same as the output plot"
with pytest.raises(ValueError, match=msg):
fig, axes = mpl.pyplot.subplots(2, 3)
Expand Down
18 changes: 8 additions & 10 deletions pandas/tests/plotting/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,17 +222,15 @@ def test_conversion_float(self, dtc):
rs = dtc.convert(datetime(2012, 1, 1, 1, 2, 3), None, None)
tm.assert_almost_equal(rs, xp, rtol=rtol)

def test_conversion_outofbounds_datetime(self, dtc):
@pytest.mark.parametrize(
"values",
[
[date(1677, 1, 1), date(1677, 1, 2)],
[datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)],
],
)
def test_conversion_outofbounds_datetime(self, dtc, values):
# 2579
values = [date(1677, 1, 1), date(1677, 1, 2)]
rs = dtc.convert(values, None, None)
xp = converter.mdates.date2num(values)
tm.assert_numpy_array_equal(rs, xp)
rs = dtc.convert(values[0], None, None)
xp = converter.mdates.date2num(values[0])
assert rs == xp

values = [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)]
rs = dtc.convert(values, None, None)
xp = converter.mdates.date2num(values)
tm.assert_numpy_array_equal(rs, xp)
Expand Down
Loading