From 7e426f6031d239ce55c51c97b6eb5501282e461d Mon Sep 17 00:00:00 2001 From: Phillip Cloud Date: Wed, 18 Sep 2013 13:23:20 -0400 Subject: [PATCH 1/2] CLN: clean up test_graphics.py --- pandas/tests/test_graphics.py | 245 +++++++++++++++++++--------------- 1 file changed, 140 insertions(+), 105 deletions(-) diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 45289dac44254..cb6ec3d648afa 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -67,17 +67,16 @@ def test_plot(self): _check_plot_works(self.series[:5].plot, kind='line') _check_plot_works(self.series[:5].plot, kind='barh') _check_plot_works(self.series[:10].plot, kind='barh') - - Series(randn(10)).plot(kind='bar', color='black') + _check_plot_works(Series(randn(10)).plot, kind='bar', color='black') # figsize and title import matplotlib.pyplot as plt plt.close('all') ax = self.series.plot(title='Test', figsize=(16, 8)) - self.assert_(ax.title.get_text() == 'Test') - self.assert_((np.round(ax.figure.get_size_inches()) - == np.array((16., 8.))).all()) + self.assertEqual(ax.title.get_text(), 'Test') + assert_array_equal(np.round(ax.figure.get_size_inches()), + np.array((16., 8.))) @slow def test_bar_colors(self): @@ -97,7 +96,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = conv.to_rgba(default_colors[i % len(default_colors)]) rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -109,7 +108,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = conv.to_rgba(custom_colors[i]) rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -124,7 +123,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = rgba_colors[i] rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -137,7 +136,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = rgba_colors[i] rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -150,18 +149,18 @@ def test_bar_linewidth(self): # regular ax = df.plot(kind='bar', linewidth=2) for r in ax.patches: - self.assert_(r.get_linewidth() == 2) + self.assertEqual(r.get_linewidth(), 2) # stacked ax = df.plot(kind='bar', stacked=True, linewidth=2) for r in ax.patches: - self.assert_(r.get_linewidth() == 2) + self.assertEqual(r.get_linewidth(), 2) # subplots axes = df.plot(kind='bar', linewidth=2, subplots=True) for ax in axes: for r in ax.patches: - self.assert_(r.get_linewidth() == 2) + self.assertEqual(r.get_linewidth(), 2) @slow def test_bar_log(self): @@ -177,7 +176,7 @@ def test_rotation(self): df = DataFrame(randn(5, 5)) ax = df.plot(rot=30) for l in ax.get_xticklabels(): - self.assert_(l.get_rotation() == 30) + self.assertEqual(l.get_rotation(), 30) def test_irregular_datetime(self): rng = date_range('1/1/2000', '3/1/2000') @@ -186,7 +185,7 @@ def test_irregular_datetime(self): ax = ser.plot() xp = datetime(1999, 1, 1).toordinal() ax.set_xlim('1/1/1999', '1/1/2001') - self.assert_(xp == ax.get_xlim()[0]) + self.assertEqual(xp, ax.get_xlim()[0]) @slow def test_hist(self): @@ -205,8 +204,9 @@ def test_hist(self): fig, (ax1, ax2) = plt.subplots(1, 2) _check_plot_works(self.ts.hist, figure=fig, ax=ax1) _check_plot_works(self.ts.hist, figure=fig, ax=ax2) - self.assertRaises(ValueError, self.ts.hist, by=self.ts.index, - figure=fig) + + with tm.assertRaises(ValueError): + self.ts.hist(by=self.ts.index, figure=fig) @slow def test_hist_layout(self): @@ -216,8 +216,11 @@ def test_hist_layout(self): size=n)], 'height': random.normal(66, 4, size=n), 'weight': random.normal(161, 32, size=n)}) - self.assertRaises(ValueError, df.height.hist, layout=(1, 1)) - self.assertRaises(ValueError, df.height.hist, layout=[1, 1]) + with tm.assertRaises(ValueError): + df.height.hist(layout=(1, 1)) + + with tm.assertRaises(ValueError): + df.height.hist(layout=[1, 1]) @slow def test_hist_layout_with_by(self): @@ -231,10 +234,13 @@ def test_hist_layout_with_by(self): 'category': random.randint(4, size=n)}) _check_plot_works(df.height.hist, by=df.gender, layout=(2, 1)) plt.close('all') + _check_plot_works(df.height.hist, by=df.gender, layout=(1, 2)) plt.close('all') + _check_plot_works(df.weight.hist, by=df.category, layout=(1, 4)) plt.close('all') + _check_plot_works(df.weight.hist, by=df.category, layout=(4, 1)) plt.close('all') @@ -250,19 +256,20 @@ def test_hist_no_overlap(self): fig = gcf() axes = fig.get_axes() self.assertEqual(len(axes), 2) - close('all') @slow def test_plot_fails_with_dupe_color_and_style(self): x = Series(randn(2)) - self.assertRaises(ValueError, x.plot, style='k--', color='k') + with tm.assertRaises(ValueError): + x.plot(style='k--', color='k') def test_plot_fails_when_ax_differs_from_figure(self): - from pylab import figure + from pylab import figure, close fig1 = figure() fig2 = figure() ax1 = fig1.add_subplot(111) - self.assertRaises(AssertionError, self.ts.hist, ax=ax1, figure=fig2) + with tm.assertRaises(AssertionError): + self.ts.hist(ax=ax1, figure=fig2) @slow def test_kde(self): @@ -311,7 +318,8 @@ def test_invalid_plot_data(self): kinds = 'line', 'bar', 'barh', 'kde', 'density' for kind in kinds: - self.assertRaises(TypeError, s.plot, kind=kind) + with tm.assertRaises(TypeError): + s.plot(kind=kind) @slow def test_valid_object_plot(self): @@ -326,11 +334,13 @@ def test_partially_invalid_plot_data(self): kinds = 'line', 'bar', 'barh', 'kde', 'density' for kind in kinds: - self.assertRaises(TypeError, s.plot, kind=kind) + with tm.assertRaises(TypeError): + s.plot(kind=kind) def test_invalid_kind(self): s = Series([1, 2]) - self.assertRaises(ValueError, s.plot, kind='aasdf') + with tm.assertRaises(ValueError): + s.plot(kind='aasdf') @slow def test_dup_datetime_index_plot(self): @@ -342,7 +352,6 @@ def test_dup_datetime_index_plot(self): _check_plot_works(s.plot) - class TestDataFramePlots(unittest.TestCase): @classmethod @@ -406,23 +415,21 @@ def test_plot(self): def test_nonnumeric_exclude(self): import matplotlib.pyplot as plt - plt.close('all') - df = DataFrame({'A': ["x", "y", "z"], 'B': [1, 2, 3]}) ax = df.plot() - self.assert_(len(ax.get_lines()) == 1) # B was plotted + self.assertEqual(len(ax.get_lines()), 1) # B was plotted @slow - def test_label(self): - import matplotlib.pyplot as plt - plt.close('all') + def test_implicit_label(self): df = DataFrame(randn(10, 3), columns=['a', 'b', 'c']) ax = df.plot(x='a', y='b') - self.assert_(ax.xaxis.get_label().get_text() == 'a') + self.assertEqual(ax.xaxis.get_label().get_text(), 'a') - plt.close('all') + @slow + def test_explicit_label(self): + df = DataFrame(randn(10, 3), columns=['a', 'b', 'c']) ax = df.plot(x='a', y='b', label='LABEL') - self.assert_(ax.xaxis.get_label().get_text() == 'LABEL') + self.assertEqual(ax.xaxis.get_label().get_text(), 'LABEL') @slow def test_plot_xy(self): @@ -449,9 +456,9 @@ def test_plot_xy(self): plt.close('all') ax = df.plot(x=1, y=2, title='Test', figsize=(16, 8)) - self.assert_(ax.title.get_text() == 'Test') - self.assert_((np.round(ax.figure.get_size_inches()) - == np.array((16., 8.))).all()) + self.assertEqual(ax.title.get_text(), 'Test') + assert_array_equal(np.round(ax.figure.get_size_inches()), + np.array((16., 8.))) # columns.inferred_type == 'mixed' # TODO add MultiIndex test @@ -541,19 +548,25 @@ def test_subplots(self): @slow def test_plot_bar(self): + from matplotlib.pylab import close df = DataFrame(randn(6, 4), index=list(string.ascii_letters[:6]), columns=['one', 'two', 'three', 'four']) _check_plot_works(df.plot, kind='bar') + close('all') _check_plot_works(df.plot, kind='bar', legend=False) + close('all') _check_plot_works(df.plot, kind='bar', subplots=True) + close('all') _check_plot_works(df.plot, kind='bar', stacked=True) + close('all') df = DataFrame(randn(10, 15), index=list(string.ascii_letters[:10]), columns=lrange(15)) _check_plot_works(df.plot, kind='bar') + close('all') df = DataFrame({'a': [0, 1], 'b': [1, 0]}) _check_plot_works(df.plot, kind='bar') @@ -608,14 +621,11 @@ def test_boxplot(self): _check_plot_works(df.boxplot) _check_plot_works(df.boxplot, column=['one', 'two']) - _check_plot_works(df.boxplot, column=['one', 'two'], - by='indic') + _check_plot_works(df.boxplot, column=['one', 'two'], by='indic') _check_plot_works(df.boxplot, column='one', by=['indic', 'indic2']) _check_plot_works(df.boxplot, by='indic') _check_plot_works(df.boxplot, by=['indic', 'indic2']) - - _check_plot_works(lambda x: plotting.boxplot(x), df['one']) - + _check_plot_works(plotting.boxplot, df['one']) _check_plot_works(df.boxplot, notch=1) _check_plot_works(df.boxplot, by='indic', notch=1) @@ -633,7 +643,7 @@ def test_kde(self): self.assert_(ax.get_legend() is not None) axes = df.plot(kind='kde', logy=True, subplots=True) for ax in axes: - self.assert_(ax.get_yscale() == 'log') + self.assertEqual(ax.get_yscale(), 'log') @slow def test_hist(self): @@ -694,11 +704,13 @@ def test_hist(self): plt.close('all') ax = ser.hist(log=True) # scale of y must be 'log' - self.assert_(ax.get_yscale() == 'log') + self.assertEqual(ax.get_yscale(), 'log') plt.close('all') + # propagate attr exception from matplotlib.Axes.hist - self.assertRaises(AttributeError, ser.hist, foo='bar') + with tm.assertRaises(AttributeError): + ser.hist(foo='bar') @slow def test_hist_layout(self): @@ -716,14 +728,16 @@ def test_hist_layout(self): for layout_test in layout_to_expected_size: ax = df.hist(layout=layout_test['layout']) - self.assert_(len(ax) == layout_test['expected_size'][0]) - self.assert_(len(ax[0]) == layout_test['expected_size'][1]) + self.assertEqual(len(ax), layout_test['expected_size'][0]) + self.assertEqual(len(ax[0]), layout_test['expected_size'][1]) # layout too small for all 4 plots - self.assertRaises(ValueError, df.hist, layout=(1, 1)) + with tm.assertRaises(ValueError): + df.hist(layout=(1, 1)) # invalid format for layout - self.assertRaises(ValueError, df.hist, layout=(1,)) + with tm.assertRaises(ValueError): + df.hist(layout=(1,)) @slow def test_scatter(self): @@ -734,6 +748,7 @@ def test_scatter(self): def scat(**kwds): return plt.scatter_matrix(df, **kwds) + _check_plot_works(scat) _check_plot_works(scat, marker='+') _check_plot_works(scat, vmin=0) @@ -752,8 +767,10 @@ def scat2(x, y, by=None, ax=None, figsize=None): def test_andrews_curves(self): from pandas import read_csv from pandas.tools.plotting import andrews_curves - path = os.path.join(curpath(), 'data/iris.csv') + + path = os.path.join(curpath(), 'data', 'iris.csv') df = read_csv(path) + _check_plot_works(andrews_curves, df, 'Name') @slow @@ -761,7 +778,7 @@ def test_parallel_coordinates(self): from pandas import read_csv from pandas.tools.plotting import parallel_coordinates from matplotlib import cm - path = os.path.join(curpath(), 'data/iris.csv') + path = os.path.join(curpath(), 'data', 'iris.csv') df = read_csv(path) _check_plot_works(parallel_coordinates, df, 'Name') _check_plot_works(parallel_coordinates, df, 'Name', @@ -774,8 +791,8 @@ def test_parallel_coordinates(self): colors=['dodgerblue', 'aquamarine', 'seagreen']) _check_plot_works(parallel_coordinates, df, 'Name', colormap=cm.jet) - df = read_csv( - path, header=None, skiprows=1, names=[1, 2, 4, 8, 'Name']) + df = read_csv(path, header=None, skiprows=1, names=[1, 2, 4, 8, + 'Name']) _check_plot_works(parallel_coordinates, df, 'Name', use_columns=True) _check_plot_works(parallel_coordinates, df, 'Name', xticks=[1, 5, 25, 125]) @@ -785,7 +802,8 @@ def test_radviz(self): from pandas import read_csv from pandas.tools.plotting import radviz from matplotlib import cm - path = os.path.join(curpath(), 'data/iris.csv') + + path = os.path.join(curpath(), 'data', 'iris.csv') df = read_csv(path) _check_plot_works(radviz, df, 'Name') _check_plot_works(radviz, df, 'Name', colormap=cm.jet) @@ -803,10 +821,11 @@ def test_legend_name(self): ax = multi.plot() leg_title = ax.legend_.get_title() - self.assert_(leg_title.get_text(), 'group,individual') + self.assertEqual(leg_title.get_text(), 'group,individual') def _check_plot_fails(self, f, *args, **kwargs): - self.assertRaises(Exception, f, *args, **kwargs) + with tm.assertRaises(Exception): + f(*args, **kwargs) @slow def test_style_by_column(self): @@ -832,7 +851,6 @@ def test_line_colors(self): custom_colors = 'rgcby' - plt.close('all') df = DataFrame(randn(5, 5)) ax = df.plot(color=custom_colors) @@ -841,7 +859,7 @@ def test_line_colors(self): for i, l in enumerate(lines): xp = custom_colors[i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) tmp = sys.stderr sys.stderr = StringIO() @@ -850,7 +868,7 @@ def test_line_colors(self): ax2 = df.plot(colors=custom_colors) lines2 = ax2.get_lines() for l1, l2 in zip(lines, lines2): - self.assert_(l1.get_color(), l2.get_color()) + self.assertEqual(l1.get_color(), l2.get_color()) finally: sys.stderr = tmp @@ -864,7 +882,7 @@ def test_line_colors(self): for i, l in enumerate(lines): xp = rgba_colors[i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -876,7 +894,7 @@ def test_line_colors(self): for i, l in enumerate(lines): xp = rgba_colors[i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) # make color a list if plotting one column frame # handles cases like df.plot(color='DodgerBlue') @@ -895,7 +913,7 @@ def test_default_color_cycle(self): for i, l in enumerate(lines): xp = plt.rcParams['axes.color_cycle'][i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) def test_unordered_ts(self): df = DataFrame(np.array([3.0, 2.0, 1.0]), @@ -907,13 +925,14 @@ def test_unordered_ts(self): xticks = ax.lines[0].get_xdata() self.assert_(xticks[0] < xticks[1]) ydata = ax.lines[0].get_ydata() - self.assert_(np.all(ydata == np.array([1.0, 2.0, 3.0]))) + assert_array_equal(ydata, np.array([1.0, 2.0, 3.0])) def test_all_invalid_plot_data(self): kinds = 'line', 'bar', 'barh', 'kde', 'density' df = DataFrame(list('abcd')) for kind in kinds: - self.assertRaises(TypeError, df.plot, kind=kind) + with tm.assertRaises(TypeError): + df.plot(kind=kind) @slow def test_partially_invalid_plot_data(self): @@ -921,11 +940,13 @@ def test_partially_invalid_plot_data(self): df = DataFrame(randn(10, 2), dtype=object) df[np.random.rand(df.shape[0]) > 0.5] = 'a' for kind in kinds: - self.assertRaises(TypeError, df.plot, kind=kind) + with tm.assertRaises(TypeError): + df.plot(kind=kind) def test_invalid_kind(self): df = DataFrame(randn(10, 2)) - self.assertRaises(ValueError, df.plot, kind='aasdf') + with tm.assertRaises(ValueError): + df.plot(kind='aasdf') class TestDataFrameGroupByPlots(unittest.TestCase): @@ -939,7 +960,8 @@ def setUpClass(cls): def tearDown(self): import matplotlib.pyplot as plt - plt.close('all') + for fignum in plt.get_fignums(): + plt.close(fignum) @slow def test_boxplot(self): @@ -955,36 +977,29 @@ def test_boxplot(self): grouped = df.groupby(level=1) _check_plot_works(grouped.boxplot) _check_plot_works(grouped.boxplot, subplots=False) + grouped = df.unstack(level=1).groupby(level=0, axis=1) _check_plot_works(grouped.boxplot) _check_plot_works(grouped.boxplot, subplots=False) def test_series_plot_color_kwargs(self): - # #1890 - import matplotlib.pyplot as plt - - plt.close('all') + # GH1890 ax = Series(np.arange(12) + 1).plot(color='green') line = ax.get_lines()[0] - self.assert_(line.get_color() == 'green') + self.assertEqual(line.get_color(), 'green') def test_time_series_plot_color_kwargs(self): # #1890 - import matplotlib.pyplot as plt - - plt.close('all') ax = Series(np.arange(12) + 1, index=date_range( '1/1/2000', periods=12)).plot(color='green') line = ax.get_lines()[0] - self.assert_(line.get_color() == 'green') + self.assertEqual(line.get_color(), 'green') def test_time_series_plot_color_with_empty_kwargs(self): import matplotlib as mpl - import matplotlib.pyplot as plt def_colors = mpl.rcParams['axes.color_cycle'] - plt.close('all') for i in range(3): ax = Series(np.arange(12) + 1, index=date_range('1/1/2000', periods=12)).plot() @@ -998,12 +1013,12 @@ def test_grouped_hist(self): df = DataFrame(randn(500, 2), columns=['A', 'B']) df['C'] = np.random.randint(0, 4, 500) axes = plotting.grouped_hist(df.A, by=df.C) - self.assert_(len(axes.ravel()) == 4) + self.assertEqual(len(axes.ravel()), 4) plt.close('all') axes = df.hist(by=df.C) - self.assert_(axes.ndim == 2) - self.assert_(len(axes.ravel()) == 4) + self.assertEqual(axes.ndim, 2) + self.assertEqual(len(axes.ravel()), 4) for ax in axes.ravel(): self.assert_(len(ax.patches) > 0) @@ -1022,12 +1037,13 @@ def test_grouped_hist(self): axes = plotting.grouped_hist(df.A, by=df.C, log=True) # scale of y must be 'log' for ax in axes.ravel(): - self.assert_(ax.get_yscale() == 'log') + self.assertEqual(ax.get_yscale(), 'log') plt.close('all') + # propagate attr exception from matplotlib.Axes.hist - self.assertRaises(AttributeError, plotting.grouped_hist, df.A, - by=df.C, foo='bar') + with tm.assertRaises(AttributeError): + plotting.grouped_hist(df.A, by=df.C, foo='bar') @slow def test_grouped_hist_layout(self): @@ -1057,49 +1073,67 @@ def test_grouped_hist_layout(self): layout=(4, 2)).shape, (4, 2)) @slow - def test_axis_shared(self): + def test_axis_share_x(self): # GH4089 - import matplotlib.pyplot as plt - def tick_text(tl): - return [x.get_text() for x in tl] - n = 100 - df = DataFrame({'gender': np.array(['Male', 'Female'])[random.randint(2, size=n)], + df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n), 'height': random.normal(66, 4, size=n), 'weight': random.normal(161, 32, size=n)}) ax1, ax2 = df.hist(column='height', by=df.gender, sharex=True) - self.assert_(ax1._shared_x_axes.joined(ax1, ax2)) + + # share x + self.assertTrue(ax1._shared_x_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_x_axes.joined(ax1, ax2)) + + # don't share y self.assertFalse(ax1._shared_y_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_x_axes.joined(ax1, ax2)) self.assertFalse(ax2._shared_y_axes.joined(ax1, ax2)) - plt.close('all') + @slow + def test_axis_share_y(self): + n = 100 + df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n), + 'height': random.normal(66, 4, size=n), + 'weight': random.normal(161, 32, size=n)}) ax1, ax2 = df.hist(column='height', by=df.gender, sharey=True) + + # share y + self.assertTrue(ax1._shared_y_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_y_axes.joined(ax1, ax2)) + + # don't share x self.assertFalse(ax1._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax1._shared_y_axes.joined(ax1, ax2)) self.assertFalse(ax2._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_y_axes.joined(ax1, ax2)) - plt.close('all') + @slow + def test_axis_share_xy(self): + n = 100 + df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n), + 'height': random.normal(66, 4, size=n), + 'weight': random.normal(161, 32, size=n)}) ax1, ax2 = df.hist(column='height', by=df.gender, sharex=True, sharey=True) - self.assert_(ax1._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax1._shared_y_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_y_axes.joined(ax1, ax2)) + + # share both x and y + self.assertTrue(ax1._shared_x_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_x_axes.joined(ax1, ax2)) + + self.assertTrue(ax1._shared_y_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_y_axes.joined(ax1, ax2)) def test_option_mpl_style(self): set_option('display.mpl_style', 'default') set_option('display.mpl_style', None) set_option('display.mpl_style', False) - try: + + with tm.assertRaises(ValueError): set_option('display.mpl_style', 'default2') - except ValueError: - pass def test_invalid_colormap(self): df = DataFrame(randn(3, 2), columns=['A', 'B']) - self.assertRaises(ValueError, df.plot, colormap='invalid_colormap') + + with tm.assertRaises(ValueError): + df.plot(colormap='invalid_colormap') def assert_is_valid_plot_return_object(objs): @@ -1141,6 +1175,7 @@ def _check_plot_works(f, *args, **kwargs): with ensure_clean() as path: plt.savefig(path) + plt.close(fig) def curpath(): From 2752aee443a52ab0caaa7fa92f0aa979ce96fda8 Mon Sep 17 00:00:00 2001 From: Phillip Cloud Date: Wed, 18 Sep 2013 15:06:03 -0400 Subject: [PATCH 2/2] CLN: clean up tseries/tests/test_plotting.py --- pandas/tseries/tests/test_plotting.py | 349 +++++++++++--------------- 1 file changed, 151 insertions(+), 198 deletions(-) diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index 87cb65601bdd9..a22d2a65248a9 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -1,9 +1,8 @@ -import os from datetime import datetime, timedelta, date, time import unittest import nose -from pandas.compat import range, lrange, zip +from pandas.compat import lrange, zip import numpy as np from numpy.testing.decorators import slow @@ -52,48 +51,49 @@ def setUp(self): columns=['A', 'B', 'C']) for x in idx] + def tearDown(self): + import matplotlib.pyplot as plt + for fignum in plt.get_fignums(): + plt.close(fignum) + @slow def test_ts_plot_with_tz(self): # GH2877 - index = date_range('1/1/2011', periods=2, freq='H', tz='Europe/Brussels') + index = date_range('1/1/2011', periods=2, freq='H', + tz='Europe/Brussels') ts = Series([188.5, 328.25], index=index) - ts.plot() + _check_plot_works(ts.plot) @slow def test_frame_inferred(self): # inferred freq import matplotlib.pyplot as plt - plt.close('all') idx = date_range('1/1/1987', freq='MS', periods=100) idx = DatetimeIndex(idx.values, freq=None) + df = DataFrame(np.random.randn(len(idx), 3), index=idx) - df.plot() + _check_plot_works(df.plot) # axes freq idx = idx[0:40] + idx[45:99] df2 = DataFrame(np.random.randn(len(idx), 3), index=idx) - df2.plot() - plt.close('all') + _check_plot_works(df2.plot) # N > 1 idx = date_range('2008-1-1 00:15:00', freq='15T', periods=10) idx = DatetimeIndex(idx.values, freq=None) df = DataFrame(np.random.randn(len(idx), 3), index=idx) - df.plot() + _check_plot_works(df.plot) - @slow def test_nonnumeric_exclude(self): import matplotlib.pyplot as plt - plt.close('all') idx = date_range('1/1/1987', freq='A', periods=3) df = DataFrame({'A': ["x", "y", "z"], 'B': [1,2,3]}, idx) - plt.close('all') ax = df.plot() # it works self.assert_(len(ax.get_lines()) == 1) #B was plotted - - plt.close('all') + plt.close(plt.gcf()) self.assertRaises(TypeError, df['A'].plot) @@ -101,30 +101,23 @@ def test_nonnumeric_exclude(self): def test_tsplot(self): from pandas.tseries.plotting import tsplot import matplotlib.pyplot as plt - plt.close('all') ax = plt.gca() ts = tm.makeTimeSeries() - tsplot(ts, plt.Axes.plot) f = lambda *args, **kwds: tsplot(s, plt.Axes.plot, *args, **kwds) - plt.close('all') for s in self.period_ser: _check_plot_works(f, s.index.freq, ax=ax, series=s) - plt.close('all') + for s in self.datetime_ser: _check_plot_works(f, s.index.freq.rule_code, ax=ax, series=s) - plt.close('all') - plt.close('all') ax = ts.plot(style='k') - self.assert_((0., 0., 0.) == ax.get_lines()[0].get_color()) + self.assertEqual((0., 0., 0.), ax.get_lines()[0].get_color()) - @slow def test_both_style_and_color(self): import matplotlib.pyplot as plt - plt.close('all') ts = tm.makeTimeSeries() self.assertRaises(ValueError, ts.plot, style='b-', color='#000099') @@ -143,11 +136,11 @@ def test_high_freq(self): def test_get_datevalue(self): from pandas.tseries.converter import get_datevalue self.assert_(get_datevalue(None, 'D') is None) - self.assert_(get_datevalue(1987, 'A') == 1987) - self.assert_(get_datevalue(Period(1987, 'A'), 'M') == - Period('1987-12', 'M').ordinal) - self.assert_(get_datevalue('1/1/1987', 'D') == - Period('1987-1-1', 'D').ordinal) + self.assertEqual(get_datevalue(1987, 'A'), 1987) + self.assertEqual(get_datevalue(Period(1987, 'A'), 'M'), + Period('1987-12', 'M').ordinal) + self.assertEqual(get_datevalue('1/1/1987', 'D'), + Period('1987-1-1', 'D').ordinal) @slow def test_line_plot_period_series(self): @@ -179,7 +172,6 @@ def test_line_plot_inferred_freq(self): ser = ser[[0, 3, 5, 6]] _check_plot_works(ser.plot) - @slow def test_fake_inferred_business(self): import matplotlib.pyplot as plt fig = plt.gcf() @@ -189,7 +181,7 @@ def test_fake_inferred_business(self): ts = Series(lrange(len(rng)), rng) ts = ts[:3].append(ts[5:]) ax = ts.plot() - self.assert_(not hasattr(ax, 'freq')) + self.assertFalse(hasattr(ax, 'freq')) @slow def test_plot_offset_freq(self): @@ -227,8 +219,8 @@ def test_uhf(self): for loc, label in zip(tlocs, tlabels): xp = conv._from_ordinal(loc).strftime('%H:%M:%S.%f') rs = str(label.get_text()) - if len(rs) != 0: - self.assert_(xp == rs) + if len(rs): + self.assertEqual(xp, rs) @slow def test_irreg_hf(self): @@ -255,7 +247,6 @@ def test_irreg_hf(self): diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff() self.assert_((np.fabs(diffs[1:] - sec) < 1e-8).all()) - @slow def test_irregular_datetime64_repr_bug(self): import matplotlib.pyplot as plt ser = tm.makeTimeSeries() @@ -265,56 +256,52 @@ def test_irregular_datetime64_repr_bug(self): plt.clf() ax = fig.add_subplot(211) ret = ser.plot() - assert(ret is not None) + self.assert_(ret is not None) for rs, xp in zip(ax.get_lines()[0].get_xdata(), ser.index): - assert(rs == xp) + self.assertEqual(rs, xp) - @slow def test_business_freq(self): import matplotlib.pyplot as plt - plt.close('all') bts = tm.makePeriodSeries() ax = bts.plot() - self.assert_(ax.get_lines()[0].get_xydata()[0, 0], - bts.index[0].ordinal) + self.assertEqual(ax.get_lines()[0].get_xydata()[0, 0], + bts.index[0].ordinal) idx = ax.get_lines()[0].get_xdata() - self.assert_(PeriodIndex(data=idx).freqstr == 'B') + self.assertEqual(PeriodIndex(data=idx).freqstr, 'B') @slow def test_business_freq_convert(self): - import matplotlib.pyplot as plt - plt.close('all') n = tm.N tm.N = 300 bts = tm.makeTimeSeries().asfreq('BM') tm.N = n ts = bts.to_period('M') ax = bts.plot() - self.assert_(ax.get_lines()[0].get_xydata()[0, 0], ts.index[0].ordinal) + self.assertEqual(ax.get_lines()[0].get_xydata()[0, 0], + ts.index[0].ordinal) idx = ax.get_lines()[0].get_xdata() - self.assert_(PeriodIndex(data=idx).freqstr == 'M') + self.assertEqual(PeriodIndex(data=idx).freqstr, 'M') - @slow def test_nonzero_base(self): - import matplotlib.pyplot as plt - plt.close('all') - #GH2571 + # GH2571 idx = (date_range('2012-12-20', periods=24, freq='H') + timedelta(minutes=30)) df = DataFrame(np.arange(24), index=idx) ax = df.plot() rs = ax.get_lines()[0].get_xdata() - self.assert_(not Index(rs).is_normalized) + self.assertFalse(Index(rs).is_normalized) - @slow def test_dataframe(self): bts = DataFrame({'a': tm.makeTimeSeries()}) ax = bts.plot() idx = ax.get_lines()[0].get_xdata() + assert_array_equal(bts.index.to_period(), idx) @slow def test_axis_limits(self): + import matplotlib.pyplot as plt + def _test(ax): xlim = ax.get_xlim() ax.set_xlim(xlim[0] - 5, xlim[1] + 10) @@ -340,9 +327,7 @@ def _test(ax): result = ax.get_xlim() self.assertEqual(int(result[0]), expected[0].ordinal) self.assertEqual(int(result[1]), expected[1].ordinal) - - import matplotlib.pyplot as plt - plt.close('all') + plt.close(ax.get_figure()) ser = tm.makeTimeSeries() ax = ser.plot() @@ -354,7 +339,9 @@ def _test(ax): df = DataFrame({'a': ser, 'b': ser + 1}) axes = df.plot(subplots=True) - [_test(ax) for ax in axes] + + for ax in axes: + _test(ax) def test_get_finder(self): import pandas.tseries.converter as conv @@ -368,6 +355,7 @@ def test_get_finder(self): @slow def test_finder_daily(self): + import matplotlib.pyplot as plt xp = Period('1999-1-1', freq='B').ordinal day_lst = [10, 40, 252, 400, 950, 2750, 10000] for n in day_lst: @@ -377,35 +365,35 @@ def test_finder_daily(self): xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) - (vmin, vmax) = ax.get_xlim() + vmin, vmax = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) + plt.close(ax.get_figure()) @slow def test_finder_quarterly(self): import matplotlib.pyplot as plt xp = Period('1988Q1').ordinal yrs = [3.5, 11] - plt.close('all') for n in yrs: rng = period_range('1987Q2', periods=int(n * 4), freq='Q') ser = Series(np.random.randn(len(rng)), rng) ax = ser.plot() xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] - self.assert_(rs == xp) + self.assertEqual(rs, xp) (vmin, vmax) = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) + plt.close(ax.get_figure()) @slow def test_finder_monthly(self): import matplotlib.pyplot as plt xp = Period('Jan 1988').ordinal yrs = [1.15, 2.5, 4, 11] - plt.close('all') for n in yrs: rng = period_range('1987Q2', periods=int(n * 12), freq='M') ser = Series(np.random.randn(len(rng)), rng) @@ -413,28 +401,24 @@ def test_finder_monthly(self): xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] self.assert_(rs == xp) - (vmin, vmax) = ax.get_xlim() + vmin, vmax = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) - plt.close('all') + plt.close(ax.get_figure()) - @slow def test_finder_monthly_long(self): - import matplotlib.pyplot as plt - plt.close('all') rng = period_range('1988Q1', periods=24 * 12, freq='M') ser = Series(np.random.randn(len(rng)), rng) ax = ser.plot() xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] xp = Period('1989Q1', 'M').ordinal - self.assert_(rs == xp) + self.assertEqual(rs, xp) @slow def test_finder_annual(self): import matplotlib.pyplot as plt - plt.close('all') xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170] for i, nyears in enumerate([5, 10, 19, 49, 99, 199, 599, 1001]): rng = period_range('1987', periods=nyears, freq='A') @@ -442,13 +426,11 @@ def test_finder_annual(self): ax = ser.plot() xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] - self.assert_(rs == Period(xp[i], freq='A').ordinal) - plt.close('all') + self.assertEqual(rs, Period(xp[i], freq='A').ordinal) + plt.close(ax.get_figure()) @slow def test_finder_minutely(self): - import matplotlib.pyplot as plt - plt.close('all') nminutes = 50 * 24 * 60 rng = date_range('1/1/1999', freq='Min', periods=nminutes) ser = Series(np.random.randn(len(rng)), rng) @@ -458,10 +440,7 @@ def test_finder_minutely(self): xp = Period('1/1/1999', freq='Min').ordinal self.assertEqual(rs, xp) - @slow def test_finder_hourly(self): - import matplotlib.pyplot as plt - plt.close('all') nhours = 23 rng = date_range('1/1/1999', freq='H', periods=nhours) ser = Series(np.random.randn(len(rng)), rng) @@ -474,40 +453,40 @@ def test_finder_hourly(self): @slow def test_gaps(self): import matplotlib.pyplot as plt - plt.close('all') + ts = tm.makeTimeSeries() ts[5:25] = np.nan ax = ts.plot() lines = ax.get_lines() - self.assert_(len(lines) == 1) + self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assert_(mask[5:25, 1].all()) + plt.close(ax.get_figure()) # irregular - plt.close('all') ts = tm.makeTimeSeries() ts = ts[[0, 1, 2, 5, 7, 9, 12, 15, 20]] ts[2:5] = np.nan ax = ts.plot() lines = ax.get_lines() - self.assert_(len(lines) == 1) + self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assert_(mask[2:5, 1].all()) + plt.close(ax.get_figure()) # non-ts - plt.close('all') idx = [0, 1, 2, 5, 7, 9, 12, 15, 20] ser = Series(np.random.randn(len(idx)), idx) ser[2:5] = np.nan ax = ser.plot() lines = ax.get_lines() - self.assert_(len(lines) == 1) + self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) @@ -516,8 +495,6 @@ def test_gaps(self): @slow def test_gap_upsample(self): - import matplotlib.pyplot as plt - plt.close('all') low = tm.makeTimeSeries() low[5:25] = np.nan ax = low.plot() @@ -526,8 +503,8 @@ def test_gap_upsample(self): s = Series(np.random.randn(len(idxh)), idxh) s.plot(secondary_y=True) lines = ax.get_lines() - self.assert_(len(lines) == 1) - self.assert_(len(ax.right_ax.get_lines()) == 1) + self.assertEqual(len(lines), 1) + self.assertEqual(len(ax.right_ax.get_lines()), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) @@ -537,7 +514,7 @@ def test_gap_upsample(self): @slow def test_secondary_y(self): import matplotlib.pyplot as plt - plt.close('all') + ser = Series(np.random.randn(10)) ser2 = Series(np.random.randn(10)) ax = ser.plot(secondary_y=True).right_ax @@ -546,23 +523,21 @@ def test_secondary_y(self): l = ax.get_lines()[0] xp = Series(l.get_ydata(), l.get_xdata()) assert_series_equal(ser, xp) - self.assert_(ax.get_yaxis().get_ticks_position() == 'right') - self.assert_(not axes[0].get_yaxis().get_visible()) + self.assertEqual(ax.get_yaxis().get_ticks_position(), 'right') + self.assertFalse(axes[0].get_yaxis().get_visible()) + plt.close(fig) ax2 = ser2.plot() - self.assert_(ax2.get_yaxis().get_ticks_position() == 'left') + self.assertEqual(ax2.get_yaxis().get_ticks_position(), 'default') + plt.close(ax2.get_figure()) - plt.close('all') ax = ser2.plot() ax2 = ser.plot(secondary_y=True).right_ax self.assert_(ax.get_yaxis().get_visible()) - plt.close('all') - @slow def test_secondary_y_ts(self): import matplotlib.pyplot as plt - plt.close('all') idx = date_range('1/1/2000', periods=10) ser = Series(np.random.randn(10), idx) ser2 = Series(np.random.randn(10), idx) @@ -572,13 +547,14 @@ def test_secondary_y_ts(self): l = ax.get_lines()[0] xp = Series(l.get_ydata(), l.get_xdata()).to_timestamp() assert_series_equal(ser, xp) - self.assert_(ax.get_yaxis().get_ticks_position() == 'right') - self.assert_(not axes[0].get_yaxis().get_visible()) + self.assertEqual(ax.get_yaxis().get_ticks_position(), 'right') + self.assertFalse(axes[0].get_yaxis().get_visible()) + plt.close(fig) ax2 = ser2.plot() - self.assert_(ax2.get_yaxis().get_ticks_position() == 'left') + self.assertEqual(ax2.get_yaxis().get_ticks_position(), 'default') + plt.close(ax2.get_figure()) - plt.close('all') ax = ser2.plot() ax2 = ser.plot(secondary_y=True) self.assert_(ax.get_yaxis().get_visible()) @@ -588,50 +564,41 @@ def test_secondary_kde(self): _skip_if_no_scipy() import matplotlib.pyplot as plt - plt.close('all') ser = Series(np.random.randn(10)) ax = ser.plot(secondary_y=True, kind='density').right_ax fig = ax.get_figure() axes = fig.get_axes() - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'right') @slow def test_secondary_bar(self): - import matplotlib.pyplot as plt - plt.close('all') ser = Series(np.random.randn(10)) ax = ser.plot(secondary_y=True, kind='bar') fig = ax.get_figure() axes = fig.get_axes() - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'right') @slow def test_secondary_frame(self): - import matplotlib.pyplot as plt - plt.close('all') df = DataFrame(np.random.randn(5, 3), columns=['a', 'b', 'c']) axes = df.plot(secondary_y=['a', 'c'], subplots=True) - self.assert_(axes[0].get_yaxis().get_ticks_position() == 'right') - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'default') - self.assert_(axes[2].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[0].get_yaxis().get_ticks_position(), 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'default') + self.assertEqual(axes[2].get_yaxis().get_ticks_position(), 'right') @slow def test_secondary_bar_frame(self): - import matplotlib.pyplot as plt - plt.close('all') df = DataFrame(np.random.randn(5, 3), columns=['a', 'b', 'c']) axes = df.plot(kind='bar', secondary_y=['a', 'c'], subplots=True) - self.assert_(axes[0].get_yaxis().get_ticks_position() == 'right') - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'default') - self.assert_(axes[2].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[0].get_yaxis().get_ticks_position(), 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'default') + self.assertEqual(axes[2].get_yaxis().get_ticks_position(), 'right') - @slow def test_mixed_freq_regular_first(self): import matplotlib.pyplot as plt - plt.close('all') s1 = tm.makeTimeSeries() s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]] - s1.plot() + ax = s1.plot() ax2 = s2.plot(style='g') lines = ax2.get_lines() idx1 = lines[0].get_xdata() @@ -640,30 +607,24 @@ def test_mixed_freq_regular_first(self): self.assert_(idx2.equals(s2.index.to_period('B'))) left, right = ax2.get_xlim() pidx = s1.index.to_period() - self.assert_(left == pidx[0].ordinal) - self.assert_(right == pidx[-1].ordinal) - plt.close('all') + self.assertEqual(left, pidx[0].ordinal) + self.assertEqual(right, pidx[-1].ordinal) @slow def test_mixed_freq_irregular_first(self): import matplotlib.pyplot as plt - plt.close('all') s1 = tm.makeTimeSeries() s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]] s2.plot(style='g') ax = s1.plot() - self.assert_(not hasattr(ax, 'freq')) + self.assertFalse(hasattr(ax, 'freq')) lines = ax.get_lines() x1 = lines[0].get_xdata() assert_array_equal(x1, s2.index.asobject.values) x2 = lines[1].get_xdata() assert_array_equal(x2, s1.index.asobject.values) - plt.close('all') - @slow def test_mixed_freq_hf_first(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=365, freq='D') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -671,27 +632,26 @@ def test_mixed_freq_hf_first(self): high.plot() ax = low.plot() for l in ax.get_lines(): - self.assert_(PeriodIndex(data=l.get_xdata()).freq == 'D') + self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, 'D') @slow def test_mixed_freq_alignment(self): - import matplotlib.pyplot as plt ts_ind = date_range('2012-01-01 13:00', '2012-01-02', freq='H') ts_data = np.random.randn(12) ts = Series(ts_data, index=ts_ind) ts2 = ts.asfreq('T').interpolate() - plt.close('all') ax = ts.plot() ts2.plot(style='r') - self.assert_(ax.lines[0].get_xdata()[0] == ax.lines[1].get_xdata()[0]) + self.assertEqual(ax.lines[0].get_xdata()[0], + ax.lines[1].get_xdata()[0]) @slow def test_mixed_freq_lf_first(self): import matplotlib.pyplot as plt - plt.close('all') + idxh = date_range('1/1/1999', periods=365, freq='D') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -699,11 +659,11 @@ def test_mixed_freq_lf_first(self): low.plot(legend=True) ax = high.plot(legend=True) for l in ax.get_lines(): - self.assert_(PeriodIndex(data=l.get_xdata()).freq == 'D') + self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, 'D') leg = ax.get_legend() - self.assert_(len(leg.texts) == 2) + self.assertEqual(len(leg.texts), 2) + plt.close(ax.get_figure()) - plt.close('all') idxh = date_range('1/1/1999', periods=240, freq='T') idxl = date_range('1/1/1999', periods=4, freq='H') high = Series(np.random.randn(len(idxh)), idxh) @@ -711,9 +671,8 @@ def test_mixed_freq_lf_first(self): low.plot() ax = high.plot() for l in ax.get_lines(): - self.assert_(PeriodIndex(data=l.get_xdata()).freq == 'T') + self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, 'T') - @slow def test_mixed_freq_irreg_period(self): ts = tm.makeTimeSeries() irreg = ts[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]] @@ -724,8 +683,6 @@ def test_mixed_freq_irreg_period(self): @slow def test_to_weekly_resampling(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=52, freq='W') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -737,8 +694,6 @@ def test_to_weekly_resampling(self): @slow def test_from_weekly_resampling(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=52, freq='W') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -763,9 +718,6 @@ def test_irreg_dtypes(self): @slow def test_time(self): - import matplotlib.pyplot as plt - plt.close('all') - t = datetime(1, 1, 1, 3, 30, 0) deltas = np.random.randint(1, 20, 3).cumsum() ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas]) @@ -783,7 +735,7 @@ def test_time(self): xp = l.get_text() if len(xp) > 0: rs = time(h, m, s).strftime('%H:%M:%S') - self.assert_(xp, rs) + self.assertEqual(xp, rs) # change xlim ax.set_xlim('1:30', '5:00') @@ -797,13 +749,10 @@ def test_time(self): xp = l.get_text() if len(xp) > 0: rs = time(h, m, s).strftime('%H:%M:%S') - self.assert_(xp, rs) + self.assertEqual(xp, rs) @slow def test_time_musec(self): - import matplotlib.pyplot as plt - plt.close('all') - t = datetime(1, 1, 1, 3, 30, 0) deltas = np.random.randint(1, 20, 3).cumsum() ts = np.array([(t + timedelta(microseconds=int(x))).time() @@ -823,12 +772,10 @@ def test_time_musec(self): xp = l.get_text() if len(xp) > 0: rs = time(h, m, s).strftime('%H:%M:%S.%f') - self.assert_(xp, rs) + self.assertEqual(xp, rs) @slow def test_secondary_upsample(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=365, freq='D') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -836,9 +783,9 @@ def test_secondary_upsample(self): low.plot() ax = high.plot(secondary_y=True) for l in ax.get_lines(): - self.assert_(l.get_xdata().freq == 'D') + self.assertEqual(l.get_xdata().freq, 'D') for l in ax.right_ax.get_lines(): - self.assert_(l.get_xdata().freq == 'D') + self.assertEqual(l.get_xdata().freq, 'D') @slow def test_secondary_legend(self): @@ -851,54 +798,54 @@ def test_secondary_legend(self): df = tm.makeTimeDataFrame() ax = df.plot(secondary_y=['A', 'B']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) - self.assert_(leg.get_texts()[0].get_text() == 'A (right)') - self.assert_(leg.get_texts()[1].get_text() == 'B (right)') - self.assert_(leg.get_texts()[2].get_text() == 'C') - self.assert_(leg.get_texts()[3].get_text() == 'D') + self.assertEqual(len(leg.get_lines()), 4) + self.assertEqual(leg.get_texts()[0].get_text(), 'A (right)') + self.assertEqual(leg.get_texts()[1].get_text(), 'B (right)') + self.assertEqual(leg.get_texts()[2].get_text(), 'C') + self.assertEqual(leg.get_texts()[3].get_text(), 'D') self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) plt.clf() ax = fig.add_subplot(211) ax = df.plot(secondary_y=['A', 'C'], mark_right=False) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) - self.assert_(leg.get_texts()[0].get_text() == 'A') - self.assert_(leg.get_texts()[1].get_text() == 'B') - self.assert_(leg.get_texts()[2].get_text() == 'C') - self.assert_(leg.get_texts()[3].get_text() == 'D') + self.assertEqual(len(leg.get_lines()), 4) + self.assertEqual(leg.get_texts()[0].get_text(), 'A') + self.assertEqual(leg.get_texts()[1].get_text(), 'B') + self.assertEqual(leg.get_texts()[2].get_text(), 'C') + self.assertEqual(leg.get_texts()[3].get_text(), 'D') plt.clf() ax = df.plot(kind='bar', secondary_y=['A']) leg = ax.get_legend() - self.assert_(leg.get_texts()[0].get_text() == 'A (right)') - self.assert_(leg.get_texts()[1].get_text() == 'B') + self.assertEqual(leg.get_texts()[0].get_text(), 'A (right)') + self.assertEqual(leg.get_texts()[1].get_text(), 'B') plt.clf() ax = df.plot(kind='bar', secondary_y=['A'], mark_right=False) leg = ax.get_legend() - self.assert_(leg.get_texts()[0].get_text() == 'A') - self.assert_(leg.get_texts()[1].get_text() == 'B') + self.assertEqual(leg.get_texts()[0].get_text(), 'A') + self.assertEqual(leg.get_texts()[1].get_text(), 'B') plt.clf() ax = fig.add_subplot(211) df = tm.makeTimeDataFrame() ax = df.plot(secondary_y=['C', 'D']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) + self.assertEqual(len(leg.get_lines()), 4) self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) # non-ts df = tm.makeDataFrame() @@ -906,29 +853,28 @@ def test_secondary_legend(self): ax = fig.add_subplot(211) ax = df.plot(secondary_y=['A', 'B']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) + self.assertEqual(len(leg.get_lines()), 4) self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) plt.clf() ax = fig.add_subplot(211) ax = df.plot(secondary_y=['C', 'D']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) + self.assertEqual(len(leg.get_lines()), 4) self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) - @slow def test_format_date_axis(self): rng = date_range('1/1/2012', periods=12, freq='M') df = DataFrame(np.random.randn(len(rng), 3), rng) @@ -936,14 +882,15 @@ def test_format_date_axis(self): xaxis = ax.get_xaxis() for l in xaxis.get_ticklabels(): if len(l.get_text()) > 0: - self.assert_(l.get_rotation() == 30) + self.assertEqual(l.get_rotation(), 30) @slow def test_ax_plot(self): + import matplotlib.pyplot as plt + x = DatetimeIndex(start='2012-01-02', periods=10, freq='D') y = lrange(len(x)) - import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) lines = ax.plot(x, y, label='Y') @@ -971,39 +918,45 @@ def test_mpl_nopandas(self): assert_array_equal(np.array([x.toordinal() for x in dates]), line2.get_xydata()[:, 0]) + def _check_plot_works(f, freq=None, series=None, *args, **kwargs): import matplotlib.pyplot as plt fig = plt.gcf() - plt.clf() - ax = fig.add_subplot(211) - orig_ax = kwargs.pop('ax', plt.gca()) - orig_axfreq = getattr(orig_ax, 'freq', None) - - ret = f(*args, **kwargs) - assert(ret is not None) # do something more intelligent - - ax = kwargs.pop('ax', plt.gca()) - if series is not None: - dfreq = series.index.freq - if isinstance(dfreq, DateOffset): - dfreq = dfreq.rule_code - if orig_axfreq is None: - assert(ax.freq == dfreq) - - if freq is not None and orig_axfreq is None: - assert(ax.freq == freq) - - ax = fig.add_subplot(212) + try: - kwargs['ax'] = ax + plt.clf() + ax = fig.add_subplot(211) + orig_ax = kwargs.pop('ax', plt.gca()) + orig_axfreq = getattr(orig_ax, 'freq', None) + ret = f(*args, **kwargs) - assert(ret is not None) # do something more intelligent - except Exception: - pass + assert ret is not None # do something more intelligent + + ax = kwargs.pop('ax', plt.gca()) + if series is not None: + dfreq = series.index.freq + if isinstance(dfreq, DateOffset): + dfreq = dfreq.rule_code + if orig_axfreq is None: + assert ax.freq == dfreq + + if freq is not None and orig_axfreq is None: + assert ax.freq == freq + + ax = fig.add_subplot(212) + try: + kwargs['ax'] = ax + ret = f(*args, **kwargs) + assert ret is not None # do something more intelligent + except Exception: + pass + + with ensure_clean() as path: + plt.savefig(path) + finally: + plt.close(fig) - with ensure_clean() as path: - plt.savefig(path) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],