Skip to content

CLN: Plotting tests 2 #58910

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 4 commits into from
Jun 4, 2024
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
29 changes: 11 additions & 18 deletions pandas/tests/plotting/test_boxplot_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ def _check_ax_limits(col, ax):
class TestDataFramePlots:
def test_stacked_boxplot_set_axis(self):
# GH2980
import matplotlib.pyplot as plt

n = 80
n = 30
df = DataFrame(
{
"Clinical": np.random.default_rng(2).choice([0, 1, 2, 3], n),
Expand All @@ -51,10 +49,10 @@ def test_stacked_boxplot_set_axis(self):
)
ax = df.plot(kind="bar", stacked=True)
assert [int(x.get_text()) for x in ax.get_xticklabels()] == df.index.to_list()
ax.set_xticks(np.arange(0, 80, 10))
ax.set_xticks(np.arange(0, n, 10))
plt.draw() # Update changes
assert [int(x.get_text()) for x in ax.get_xticklabels()] == list(
np.arange(0, 80, 10)
np.arange(0, n, 10)
)

@pytest.mark.slow
Expand Down Expand Up @@ -227,12 +225,12 @@ def test_boxplot_numeric_data(self):
# GH 22799
df = DataFrame(
{
"a": date_range("2012-01-01", periods=100),
"b": np.random.default_rng(2).standard_normal(100),
"c": np.random.default_rng(2).standard_normal(100) + 2,
"d": date_range("2012-01-01", periods=100).astype(str),
"e": date_range("2012-01-01", periods=100, tz="UTC"),
"f": timedelta_range("1 days", periods=100),
"a": date_range("2012-01-01", periods=10),
"b": np.random.default_rng(2).standard_normal(10),
"c": np.random.default_rng(2).standard_normal(10) + 2,
"d": date_range("2012-01-01", periods=10).astype(str),
"e": date_range("2012-01-01", periods=10, tz="UTC"),
"f": timedelta_range("1 days", periods=10),
}
)
ax = df.plot(kind="box")
Expand Down Expand Up @@ -282,8 +280,6 @@ def test_color_kwd(self, colors_kwd, expected):
def test_colors_in_theme(self, scheme, expected):
# GH: 40769
df = DataFrame(np.random.default_rng(2).random((10, 2)))
import matplotlib.pyplot as plt

plt.style.use(scheme)
result = df.plot.box(return_type="dict")
for k, v in expected.items():
Expand Down Expand Up @@ -334,8 +330,8 @@ def test_plot_xlabel_ylabel(self, vert):
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"))
df1 = DataFrame(rng.integers(0, 100, size=(10, 4)), columns=list("ABCD"))
df2 = DataFrame(rng.integers(0, 100, size=(10, 4)), columns=list("ABCD"))

xlabel, ylabel = "x", "y"
_, axs = plt.subplots(ncols=2, figsize=(10, 7), sharey=True)
Expand All @@ -344,7 +340,6 @@ def test_plot_box(self, vert):
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):
Expand Down Expand Up @@ -374,7 +369,6 @@ def test_boxplot_group_xlabel_ylabel(self, vert):
for subplot in ax:
assert subplot.get_xlabel() == xlabel
assert subplot.get_ylabel() == ylabel
mpl.pyplot.close()

@pytest.mark.parametrize("vert", [True, False])
def test_boxplot_group_no_xlabel_ylabel(self, vert):
Expand All @@ -389,7 +383,6 @@ def test_boxplot_group_no_xlabel_ylabel(self, vert):
for subplot in ax:
target_label = subplot.get_xlabel() if vert else subplot.get_ylabel()
assert target_label == pprint_thing(["group"])
mpl.pyplot.close()


class TestDataFrameGroupByPlots:
Expand Down
28 changes: 5 additions & 23 deletions pandas/tests/plotting/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,11 @@
Second,
)

try:
from pandas.plotting._matplotlib import converter
except ImportError:
# try / except, rather than skip, to avoid internal refactoring
# causing an improper skip
pass

pytest.importorskip("matplotlib.pyplot")
plt = pytest.importorskip("matplotlib.pyplot")
dates = pytest.importorskip("matplotlib.dates")
units = pytest.importorskip("matplotlib.units")

from pandas.plotting._matplotlib import converter


@pytest.mark.single_cpu
Expand Down Expand Up @@ -79,30 +75,22 @@ def test_dont_register_by_default(self):
assert subprocess.check_call(call) == 0

def test_registering_no_warning(self):
plt = pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
_, ax = plt.subplots()

# Set to the "warn" state, in case this isn't the first test run
register_matplotlib_converters()
ax.plot(s.index, s.values)
plt.close()

def test_pandas_plots_register(self):
plt = pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
# Set to the "warn" state, in case this isn't the first test run
with tm.assert_produces_warning(None) as w:
s.plot()

try:
assert len(w) == 0
finally:
plt.close()
assert len(w) == 0

def test_matplotlib_formatters(self):
units = pytest.importorskip("matplotlib.units")

# Can't make any assertion about the start state.
# We we check that toggling converters off removes it, and toggling it
# on restores it.
Expand All @@ -113,8 +101,6 @@ def test_matplotlib_formatters(self):
assert Timestamp in units.registry

def test_option_no_warning(self):
pytest.importorskip("matplotlib.pyplot")
plt = pytest.importorskip("matplotlib.pyplot")
s = Series(range(12), index=date_range("2017", periods=12))
_, ax = plt.subplots()

Expand All @@ -126,12 +112,8 @@ def test_option_no_warning(self):
register_matplotlib_converters()
with cf.option_context("plotting.matplotlib.register_converters", False):
ax.plot(s.index, s.values)
plt.close()

def test_registry_resets(self):
units = pytest.importorskip("matplotlib.units")
dates = pytest.importorskip("matplotlib.dates")

# make a copy, to reset to
original = dict(units.registry)

Expand Down
71 changes: 28 additions & 43 deletions pandas/tests/plotting/test_hist_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
)

mpl = pytest.importorskip("matplotlib")
plt = pytest.importorskip("matplotlib.pyplot")

from pandas.plotting._matplotlib.hist import _grouped_hist


@pytest.fixture
Expand Down Expand Up @@ -119,18 +122,13 @@ def test_hist_layout_with_by_shape(self, hist_df):
_check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 7))

def test_hist_no_overlap(self):
from matplotlib.pyplot import (
gcf,
subplot,
)

x = Series(np.random.default_rng(2).standard_normal(2))
y = Series(np.random.default_rng(2).standard_normal(2))
subplot(121)
plt.subplot(121)
x.hist()
subplot(122)
plt.subplot(122)
y.hist()
fig = gcf()
fig = plt.gcf()
axes = fig.axes
assert len(axes) == 2

Expand All @@ -140,10 +138,8 @@ def test_hist_by_no_extra_plots(self, hist_df):
assert len(mpl.pyplot.get_fignums()) == 1

def test_plot_fails_when_ax_differs_from_figure(self, ts):
from pylab import figure

fig1 = figure()
fig2 = figure()
fig1 = plt.figure(1)
fig2 = plt.figure(2)
ax1 = fig1.add_subplot(111)
msg = "passed axis not bound to passed figure"
with pytest.raises(AssertionError, match=msg):
Expand All @@ -169,8 +165,8 @@ def test_histtype_argument(self, histtype, expected):
)
def test_hist_with_legend(self, by, expected_axes_num, expected_layout):
# GH 6279 - Series histogram can have a legend
index = 15 * ["1"] + 15 * ["2"]
s = Series(np.random.default_rng(2).standard_normal(30), index=index, name="a")
index = 5 * ["1"] + 5 * ["2"]
s = Series(np.random.default_rng(2).standard_normal(10), index=index, name="a")
s.index.name = "b"

# Use default_axes=True when plotting method generate subplots itself
Expand All @@ -181,8 +177,8 @@ def test_hist_with_legend(self, by, expected_axes_num, expected_layout):
@pytest.mark.parametrize("by", [None, "b"])
def test_hist_with_legend_raises(self, by):
# GH 6279 - Series histogram with legend and label raises
index = 15 * ["1"] + 15 * ["2"]
s = Series(np.random.default_rng(2).standard_normal(30), index=index, name="a")
index = 5 * ["1"] + 5 * ["2"]
s = Series(np.random.default_rng(2).standard_normal(10), index=index, name="a")
s.index.name = "b"

with pytest.raises(ValueError, match="Cannot use both legend and label"):
Expand Down Expand Up @@ -331,12 +327,10 @@ def test_hist_df_legacy_layout_labelsize_rot(self, frame_or_series):

@pytest.mark.slow
def test_hist_df_legacy_rectangles(self):
from matplotlib.patches import Rectangle

ser = Series(range(10))
ax = ser.hist(cumulative=True, bins=4, density=True)
# height of last bin (index 5) must be 1.0
rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
rects = [x for x in ax.get_children() if isinstance(x, mpl.patches.Rectangle)]
tm.assert_almost_equal(rects[-1].get_height(), 1.0)

@pytest.mark.slow
Expand Down Expand Up @@ -431,12 +425,12 @@ def test_hist_layout_error(self):

# GH 9351
def test_tight_layout(self):
df = DataFrame(np.random.default_rng(2).standard_normal((100, 2)))
df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
df[2] = to_datetime(
np.random.default_rng(2).integers(
812419200000000000,
819331200000000000,
size=100,
size=10,
dtype=np.int64,
)
)
Expand Down Expand Up @@ -504,7 +498,7 @@ def test_hist_column_order_unchanged(self, column, expected):
def test_histtype_argument(self, histtype, expected):
# GH23992 Verify functioning of histtype argument
df = DataFrame(
np.random.default_rng(2).integers(1, 10, size=(100, 2)), columns=["a", "b"]
np.random.default_rng(2).integers(1, 10, size=(10, 2)), columns=["a", "b"]
)
ax = df.hist(histtype=histtype)
_check_patches_all_filled(ax, filled=expected)
Expand All @@ -519,9 +513,9 @@ def test_hist_with_legend(self, by, column):
if by is not None:
expected_labels = [expected_labels] * 2

index = Index(15 * ["1"] + 15 * ["2"], name="c")
index = Index(5 * ["1"] + 5 * ["2"], name="c")
df = DataFrame(
np.random.default_rng(2).standard_normal((30, 2)),
np.random.default_rng(2).standard_normal((10, 2)),
index=index,
columns=["a", "b"],
)
Expand All @@ -545,9 +539,9 @@ def test_hist_with_legend(self, by, column):
@pytest.mark.parametrize("column", [None, "b"])
def test_hist_with_legend_raises(self, by, column):
# GH 6279 - DataFrame histogram with legend and label raises
index = Index(15 * ["1"] + 15 * ["2"], name="c")
index = Index(5 * ["1"] + 5 * ["2"], name="c")
df = DataFrame(
np.random.default_rng(2).standard_normal((30, 2)),
np.random.default_rng(2).standard_normal((10, 2)),
index=index,
columns=["a", "b"],
)
Expand Down Expand Up @@ -586,7 +580,7 @@ def test_hist_df_with_nonnumerics_no_bins(self):
def test_hist_secondary_legend(self):
# GH 9610
df = DataFrame(
np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
np.random.default_rng(2).standard_normal((10, 4)), columns=list("abcd")
)

# primary -> secondary
Expand All @@ -602,7 +596,7 @@ def test_hist_secondary_legend(self):
def test_hist_secondary_secondary(self):
# GH 9610
df = DataFrame(
np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
np.random.default_rng(2).standard_normal((10, 4)), columns=list("abcd")
)
# secondary -> secondary
_, ax = mpl.pyplot.subplots()
Expand All @@ -617,7 +611,7 @@ def test_hist_secondary_secondary(self):
def test_hist_secondary_primary(self):
# GH 9610
df = DataFrame(
np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
np.random.default_rng(2).standard_normal((10, 4)), columns=list("abcd")
)
# secondary -> primary
_, ax = mpl.pyplot.subplots()
Expand All @@ -632,7 +626,6 @@ def test_hist_secondary_primary(self):

def test_hist_with_nans_and_weights(self):
# GH 48884
mpl_patches = pytest.importorskip("matplotlib.patches")
df = DataFrame(
[[np.nan, 0.2, 0.3], [0.4, np.nan, np.nan], [0.7, 0.8, 0.9]],
columns=list("abc"),
Expand All @@ -643,12 +636,12 @@ def test_hist_with_nans_and_weights(self):

_, ax0 = mpl.pyplot.subplots()
df.plot.hist(ax=ax0, weights=weights)
rects = [x for x in ax0.get_children() if isinstance(x, mpl_patches.Rectangle)]
rects = [x for x in ax0.get_children() if isinstance(x, mpl.patches.Rectangle)]
heights = [rect.get_height() for rect in rects]
_, ax1 = mpl.pyplot.subplots()
no_nan_df.plot.hist(ax=ax1, weights=no_nan_weights)
no_nan_rects = [
x for x in ax1.get_children() if isinstance(x, mpl_patches.Rectangle)
x for x in ax1.get_children() if isinstance(x, mpl.patches.Rectangle)
]
no_nan_heights = [rect.get_height() for rect in no_nan_rects]
assert all(h0 == h1 for h0, h1 in zip(heights, no_nan_heights))
Expand All @@ -663,8 +656,6 @@ def test_hist_with_nans_and_weights(self):

class TestDataFrameGroupByPlots:
def test_grouped_hist_legacy(self):
from pandas.plotting._matplotlib.hist import _grouped_hist

rs = np.random.default_rng(10)
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
df["B"] = to_datetime(
Expand Down Expand Up @@ -716,10 +707,6 @@ def test_grouped_hist_legacy_single_key(self):
_check_ticks_props(axes, xrot=30)

def test_grouped_hist_legacy_grouped_hist_kwargs(self):
from matplotlib.patches import Rectangle

from pandas.plotting._matplotlib.hist import _grouped_hist

rs = np.random.default_rng(2)
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
df["B"] = to_datetime(
Expand Down Expand Up @@ -748,14 +735,14 @@ def test_grouped_hist_legacy_grouped_hist_kwargs(self):
)
# height of last bin (index 5) must be 1.0
for ax in axes.ravel():
rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
rects = [
x for x in ax.get_children() if isinstance(x, mpl.patches.Rectangle)
]
height = rects[-1].get_height()
tm.assert_almost_equal(height, 1.0)
_check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)

def test_grouped_hist_legacy_grouped_hist(self):
from pandas.plotting._matplotlib.hist import _grouped_hist

rs = np.random.default_rng(2)
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
df["B"] = to_datetime(
Expand All @@ -773,8 +760,6 @@ def test_grouped_hist_legacy_grouped_hist(self):
_check_ax_scales(axes, yaxis="log")

def test_grouped_hist_legacy_external_err(self):
from pandas.plotting._matplotlib.hist import _grouped_hist

rs = np.random.default_rng(2)
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
df["B"] = to_datetime(
Expand Down