Skip to content

Commit 728cfcb

Browse files
authored
CLN: Plotting tests 2 (#58910)
* Refactor test_converter * clean test_boxplot method * cleann test_hist_method
1 parent ea509bb commit 728cfcb

File tree

3 files changed

+44
-84
lines changed

3 files changed

+44
-84
lines changed

pandas/tests/plotting/test_boxplot_method.py

+11-18
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,7 @@ def _check_ax_limits(col, ax):
3838
class TestDataFramePlots:
3939
def test_stacked_boxplot_set_axis(self):
4040
# GH2980
41-
import matplotlib.pyplot as plt
42-
43-
n = 80
41+
n = 30
4442
df = DataFrame(
4543
{
4644
"Clinical": np.random.default_rng(2).choice([0, 1, 2, 3], n),
@@ -51,10 +49,10 @@ def test_stacked_boxplot_set_axis(self):
5149
)
5250
ax = df.plot(kind="bar", stacked=True)
5351
assert [int(x.get_text()) for x in ax.get_xticklabels()] == df.index.to_list()
54-
ax.set_xticks(np.arange(0, 80, 10))
52+
ax.set_xticks(np.arange(0, n, 10))
5553
plt.draw() # Update changes
5654
assert [int(x.get_text()) for x in ax.get_xticklabels()] == list(
57-
np.arange(0, 80, 10)
55+
np.arange(0, n, 10)
5856
)
5957

6058
@pytest.mark.slow
@@ -227,12 +225,12 @@ def test_boxplot_numeric_data(self):
227225
# GH 22799
228226
df = DataFrame(
229227
{
230-
"a": date_range("2012-01-01", periods=100),
231-
"b": np.random.default_rng(2).standard_normal(100),
232-
"c": np.random.default_rng(2).standard_normal(100) + 2,
233-
"d": date_range("2012-01-01", periods=100).astype(str),
234-
"e": date_range("2012-01-01", periods=100, tz="UTC"),
235-
"f": timedelta_range("1 days", periods=100),
228+
"a": date_range("2012-01-01", periods=10),
229+
"b": np.random.default_rng(2).standard_normal(10),
230+
"c": np.random.default_rng(2).standard_normal(10) + 2,
231+
"d": date_range("2012-01-01", periods=10).astype(str),
232+
"e": date_range("2012-01-01", periods=10, tz="UTC"),
233+
"f": timedelta_range("1 days", periods=10),
236234
}
237235
)
238236
ax = df.plot(kind="box")
@@ -282,8 +280,6 @@ def test_color_kwd(self, colors_kwd, expected):
282280
def test_colors_in_theme(self, scheme, expected):
283281
# GH: 40769
284282
df = DataFrame(np.random.default_rng(2).random((10, 2)))
285-
import matplotlib.pyplot as plt
286-
287283
plt.style.use(scheme)
288284
result = df.plot.box(return_type="dict")
289285
for k, v in expected.items():
@@ -334,8 +330,8 @@ def test_plot_xlabel_ylabel(self, vert):
334330
def test_plot_box(self, vert):
335331
# GH 54941
336332
rng = np.random.default_rng(2)
337-
df1 = DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list("ABCD"))
338-
df2 = DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list("ABCD"))
333+
df1 = DataFrame(rng.integers(0, 100, size=(10, 4)), columns=list("ABCD"))
334+
df2 = DataFrame(rng.integers(0, 100, size=(10, 4)), columns=list("ABCD"))
339335

340336
xlabel, ylabel = "x", "y"
341337
_, axs = plt.subplots(ncols=2, figsize=(10, 7), sharey=True)
@@ -344,7 +340,6 @@ def test_plot_box(self, vert):
344340
for ax in axs:
345341
assert ax.get_xlabel() == xlabel
346342
assert ax.get_ylabel() == ylabel
347-
mpl.pyplot.close()
348343

349344
@pytest.mark.parametrize("vert", [True, False])
350345
def test_boxplot_xlabel_ylabel(self, vert):
@@ -374,7 +369,6 @@ def test_boxplot_group_xlabel_ylabel(self, vert):
374369
for subplot in ax:
375370
assert subplot.get_xlabel() == xlabel
376371
assert subplot.get_ylabel() == ylabel
377-
mpl.pyplot.close()
378372

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

394387

395388
class TestDataFrameGroupByPlots:

pandas/tests/plotting/test_converter.py

+5-23
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,11 @@
3434
Second,
3535
)
3636

37-
try:
38-
from pandas.plotting._matplotlib import converter
39-
except ImportError:
40-
# try / except, rather than skip, to avoid internal refactoring
41-
# causing an improper skip
42-
pass
43-
44-
pytest.importorskip("matplotlib.pyplot")
37+
plt = pytest.importorskip("matplotlib.pyplot")
4538
dates = pytest.importorskip("matplotlib.dates")
39+
units = pytest.importorskip("matplotlib.units")
40+
41+
from pandas.plotting._matplotlib import converter
4642

4743

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

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

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

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

98-
try:
99-
assert len(w) == 0
100-
finally:
101-
plt.close()
91+
assert len(w) == 0
10292

10393
def test_matplotlib_formatters(self):
104-
units = pytest.importorskip("matplotlib.units")
105-
10694
# Can't make any assertion about the start state.
10795
# We we check that toggling converters off removes it, and toggling it
10896
# on restores it.
@@ -113,8 +101,6 @@ def test_matplotlib_formatters(self):
113101
assert Timestamp in units.registry
114102

115103
def test_option_no_warning(self):
116-
pytest.importorskip("matplotlib.pyplot")
117-
plt = pytest.importorskip("matplotlib.pyplot")
118104
s = Series(range(12), index=date_range("2017", periods=12))
119105
_, ax = plt.subplots()
120106

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

131116
def test_registry_resets(self):
132-
units = pytest.importorskip("matplotlib.units")
133-
dates = pytest.importorskip("matplotlib.dates")
134-
135117
# make a copy, to reset to
136118
original = dict(units.registry)
137119

pandas/tests/plotting/test_hist_method.py

+28-43
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@
2727
)
2828

2929
mpl = pytest.importorskip("matplotlib")
30+
plt = pytest.importorskip("matplotlib.pyplot")
31+
32+
from pandas.plotting._matplotlib.hist import _grouped_hist
3033

3134

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

121124
def test_hist_no_overlap(self):
122-
from matplotlib.pyplot import (
123-
gcf,
124-
subplot,
125-
)
126-
127125
x = Series(np.random.default_rng(2).standard_normal(2))
128126
y = Series(np.random.default_rng(2).standard_normal(2))
129-
subplot(121)
127+
plt.subplot(121)
130128
x.hist()
131-
subplot(122)
129+
plt.subplot(122)
132130
y.hist()
133-
fig = gcf()
131+
fig = plt.gcf()
134132
axes = fig.axes
135133
assert len(axes) == 2
136134

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

142140
def test_plot_fails_when_ax_differs_from_figure(self, ts):
143-
from pylab import figure
144-
145-
fig1 = figure()
146-
fig2 = figure()
141+
fig1 = plt.figure(1)
142+
fig2 = plt.figure(2)
147143
ax1 = fig1.add_subplot(111)
148144
msg = "passed axis not bound to passed figure"
149145
with pytest.raises(AssertionError, match=msg):
@@ -169,8 +165,8 @@ def test_histtype_argument(self, histtype, expected):
169165
)
170166
def test_hist_with_legend(self, by, expected_axes_num, expected_layout):
171167
# GH 6279 - Series histogram can have a legend
172-
index = 15 * ["1"] + 15 * ["2"]
173-
s = Series(np.random.default_rng(2).standard_normal(30), index=index, name="a")
168+
index = 5 * ["1"] + 5 * ["2"]
169+
s = Series(np.random.default_rng(2).standard_normal(10), index=index, name="a")
174170
s.index.name = "b"
175171

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

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

332328
@pytest.mark.slow
333329
def test_hist_df_legacy_rectangles(self):
334-
from matplotlib.patches import Rectangle
335-
336330
ser = Series(range(10))
337331
ax = ser.hist(cumulative=True, bins=4, density=True)
338332
# height of last bin (index 5) must be 1.0
339-
rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
333+
rects = [x for x in ax.get_children() if isinstance(x, mpl.patches.Rectangle)]
340334
tm.assert_almost_equal(rects[-1].get_height(), 1.0)
341335

342336
@pytest.mark.slow
@@ -431,12 +425,12 @@ def test_hist_layout_error(self):
431425

432426
# GH 9351
433427
def test_tight_layout(self):
434-
df = DataFrame(np.random.default_rng(2).standard_normal((100, 2)))
428+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))
435429
df[2] = to_datetime(
436430
np.random.default_rng(2).integers(
437431
812419200000000000,
438432
819331200000000000,
439-
size=100,
433+
size=10,
440434
dtype=np.int64,
441435
)
442436
)
@@ -504,7 +498,7 @@ def test_hist_column_order_unchanged(self, column, expected):
504498
def test_histtype_argument(self, histtype, expected):
505499
# GH23992 Verify functioning of histtype argument
506500
df = DataFrame(
507-
np.random.default_rng(2).integers(1, 10, size=(100, 2)), columns=["a", "b"]
501+
np.random.default_rng(2).integers(1, 10, size=(10, 2)), columns=["a", "b"]
508502
)
509503
ax = df.hist(histtype=histtype)
510504
_check_patches_all_filled(ax, filled=expected)
@@ -519,9 +513,9 @@ def test_hist_with_legend(self, by, column):
519513
if by is not None:
520514
expected_labels = [expected_labels] * 2
521515

522-
index = Index(15 * ["1"] + 15 * ["2"], name="c")
516+
index = Index(5 * ["1"] + 5 * ["2"], name="c")
523517
df = DataFrame(
524-
np.random.default_rng(2).standard_normal((30, 2)),
518+
np.random.default_rng(2).standard_normal((10, 2)),
525519
index=index,
526520
columns=["a", "b"],
527521
)
@@ -545,9 +539,9 @@ def test_hist_with_legend(self, by, column):
545539
@pytest.mark.parametrize("column", [None, "b"])
546540
def test_hist_with_legend_raises(self, by, column):
547541
# GH 6279 - DataFrame histogram with legend and label raises
548-
index = Index(15 * ["1"] + 15 * ["2"], name="c")
542+
index = Index(5 * ["1"] + 5 * ["2"], name="c")
549543
df = DataFrame(
550-
np.random.default_rng(2).standard_normal((30, 2)),
544+
np.random.default_rng(2).standard_normal((10, 2)),
551545
index=index,
552546
columns=["a", "b"],
553547
)
@@ -586,7 +580,7 @@ def test_hist_df_with_nonnumerics_no_bins(self):
586580
def test_hist_secondary_legend(self):
587581
# GH 9610
588582
df = DataFrame(
589-
np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
583+
np.random.default_rng(2).standard_normal((10, 4)), columns=list("abcd")
590584
)
591585

592586
# primary -> secondary
@@ -602,7 +596,7 @@ def test_hist_secondary_legend(self):
602596
def test_hist_secondary_secondary(self):
603597
# GH 9610
604598
df = DataFrame(
605-
np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
599+
np.random.default_rng(2).standard_normal((10, 4)), columns=list("abcd")
606600
)
607601
# secondary -> secondary
608602
_, ax = mpl.pyplot.subplots()
@@ -617,7 +611,7 @@ def test_hist_secondary_secondary(self):
617611
def test_hist_secondary_primary(self):
618612
# GH 9610
619613
df = DataFrame(
620-
np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd")
614+
np.random.default_rng(2).standard_normal((10, 4)), columns=list("abcd")
621615
)
622616
# secondary -> primary
623617
_, ax = mpl.pyplot.subplots()
@@ -632,7 +626,6 @@ def test_hist_secondary_primary(self):
632626

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

644637
_, ax0 = mpl.pyplot.subplots()
645638
df.plot.hist(ax=ax0, weights=weights)
646-
rects = [x for x in ax0.get_children() if isinstance(x, mpl_patches.Rectangle)]
639+
rects = [x for x in ax0.get_children() if isinstance(x, mpl.patches.Rectangle)]
647640
heights = [rect.get_height() for rect in rects]
648641
_, ax1 = mpl.pyplot.subplots()
649642
no_nan_df.plot.hist(ax=ax1, weights=no_nan_weights)
650643
no_nan_rects = [
651-
x for x in ax1.get_children() if isinstance(x, mpl_patches.Rectangle)
644+
x for x in ax1.get_children() if isinstance(x, mpl.patches.Rectangle)
652645
]
653646
no_nan_heights = [rect.get_height() for rect in no_nan_rects]
654647
assert all(h0 == h1 for h0, h1 in zip(heights, no_nan_heights))
@@ -663,8 +656,6 @@ def test_hist_with_nans_and_weights(self):
663656

664657
class TestDataFrameGroupByPlots:
665658
def test_grouped_hist_legacy(self):
666-
from pandas.plotting._matplotlib.hist import _grouped_hist
667-
668659
rs = np.random.default_rng(10)
669660
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
670661
df["B"] = to_datetime(
@@ -716,10 +707,6 @@ def test_grouped_hist_legacy_single_key(self):
716707
_check_ticks_props(axes, xrot=30)
717708

718709
def test_grouped_hist_legacy_grouped_hist_kwargs(self):
719-
from matplotlib.patches import Rectangle
720-
721-
from pandas.plotting._matplotlib.hist import _grouped_hist
722-
723710
rs = np.random.default_rng(2)
724711
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
725712
df["B"] = to_datetime(
@@ -748,14 +735,14 @@ def test_grouped_hist_legacy_grouped_hist_kwargs(self):
748735
)
749736
# height of last bin (index 5) must be 1.0
750737
for ax in axes.ravel():
751-
rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
738+
rects = [
739+
x for x in ax.get_children() if isinstance(x, mpl.patches.Rectangle)
740+
]
752741
height = rects[-1].get_height()
753742
tm.assert_almost_equal(height, 1.0)
754743
_check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
755744

756745
def test_grouped_hist_legacy_grouped_hist(self):
757-
from pandas.plotting._matplotlib.hist import _grouped_hist
758-
759746
rs = np.random.default_rng(2)
760747
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
761748
df["B"] = to_datetime(
@@ -773,8 +760,6 @@ def test_grouped_hist_legacy_grouped_hist(self):
773760
_check_ax_scales(axes, yaxis="log")
774761

775762
def test_grouped_hist_legacy_external_err(self):
776-
from pandas.plotting._matplotlib.hist import _grouped_hist
777-
778763
rs = np.random.default_rng(2)
779764
df = DataFrame(rs.standard_normal((10, 1)), columns=["A"])
780765
df["B"] = to_datetime(

0 commit comments

Comments
 (0)