<commit_before>import nose
import os
import string
import unittest

from datetime import datetime, date

from pandas import Series, DataFrame, MultiIndex, PeriodIndex, date_range
import pandas.util.testing as tm

import numpy as np

from numpy.testing import assert_array_equal
from numpy.testing.decorators import slow
import pandas.tools.plotting as plotting


def _skip_if_no_scipy():
    try:
        import scipy
    except ImportError:
        raise nose.SkipTest


class TestSeriesPlots(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        import sys

        # if 'IPython' in sys.modules:
        #     raise nose.SkipTest

        try:
            import matplotlib as mpl
            mpl.use('Agg', warn=False)
        except ImportError:
            raise nose.SkipTest

    def setUp(self):
        self.ts = tm.makeTimeSeries()
        self.ts.name = 'ts'

        self.series = tm.makeStringSeries()
        self.series.name = 'series'

        self.iseries = tm.makePeriodSeries()
        self.iseries.name = 'iseries'

    @slow
    def test_plot(self):
        _check_plot_works(self.ts.plot, label='foo')
        _check_plot_works(self.ts.plot, use_index=False)
        _check_plot_works(self.ts.plot, rot=0)
        _check_plot_works(self.ts.plot, style='.', logy=True)
        _check_plot_works(self.ts.plot, style='.', logx=True)
        _check_plot_works(self.ts.plot, style='.', loglog=True)
        _check_plot_works(self.ts[:10].plot, kind='bar')
        _check_plot_works(self.series[:5].plot, kind='bar')
        _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(np.random.randn(10)).plot(kind='bar', color='black')

    @slow
    def test_bar_colors(self):
        import matplotlib.pyplot as plt
        import matplotlib.colors as colors

        default_colors = 'brgyk'
        custom_colors = 'rgcby'

        plt.close('all')
        df = DataFrame(np.random.randn(5, 5))
        ax = df.plot(kind='bar')

        rects = ax.patches

        conv = colors.colorConverter
        for i, rect in enumerate(rects[::5]):
            xp = conv.to_rgba(default_colors[i])
            rs = rect.get_facecolor()
            self.assert_(xp == rs)

        plt.close('all')

        ax = df.plot(kind='bar', color=custom_colors)

        rects = ax.patches

        conv = colors.colorConverter
        for i, rect in enumerate(rects[::5]):
            xp = conv.to_rgba(custom_colors[i])
            rs = rect.get_facecolor()
            self.assert_(xp == rs)

        plt.close('all')
        df.ix[:, [0]].plot(kind='bar', color='DodgerBlue')

    @slow
    def test_bar_linewidth(self):
        df = DataFrame(np.random.randn(5, 5))

        # regular
        ax = df.plot(kind='bar', linewidth=2)
        for r in ax.patches:
            self.assert_(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)

        # 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)

    @slow
    def test_rotation(self):
        df = DataFrame(np.random.randn(5, 5))
        ax = df.plot(rot=30)
        for l in ax.get_xticklabels():
            self.assert_(l.get_rotation() == 30)

    @slow
    def test_irregular_datetime(self):
        rng = date_range('1/1/2000', '3/1/2000')
        rng = rng[[0, 1, 2, 3, 5, 9, 10, 11, 12]]
        ser = Series(np.random.randn(len(rng)), rng)
        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])

    @slow
    def test_hist(self):
        _check_plot_works(self.ts.hist)
        _check_plot_works(self.ts.hist, grid=False)

        _check_plot_works(self.ts.hist, by=self.ts.index.month)

    @slow
    def test_kde(self):
        _skip_if_no_scipy()
        _check_plot_works(self.ts.plot, kind='kde')
        _check_plot_works(self.ts.plot, kind='density')
        ax = self.ts.plot(kind='kde', logy=True)
        self.assert_(ax.get_yscale() == 'log')

    @slow
    def test_autocorrelation_plot(self):
        from pandas.tools.plotting import autocorrelation_plot
        _check_plot_works(autocorrelation_plot, self.ts)
        _check_plot_works(autocorrelation_plot, self.ts.values)

    @slow
    def test_lag_plot(self):
        from pandas.tools.plotting import lag_plot
        _check_plot_works(lag_plot, self.ts)
        _check_plot_works(lag_plot, self.ts, lag=5)

    @slow
    def test_bootstrap_plot(self):
        from pandas.tools.plotting import bootstrap_plot
        _check_plot_works(bootstrap_plot, self.ts, size=10)


class TestDataFramePlots(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # import sys
        # if 'IPython' in sys.modules:
        #    raise nose.SkipTest

        try:
            import matplotlib as mpl
            mpl.use('Agg', warn=False)
        except ImportError:
            raise nose.SkipTest

    @slow
    def test_plot(self):
        df = tm.makeTimeDataFrame()
        _check_plot_works(df.plot, grid=False)
        _check_plot_works(df.plot, subplots=True)
        _check_plot_works(df.plot, subplots=True, use_index=False)

        df = DataFrame({'x': [1, 2], 'y': [3, 4]})
        self._check_plot_fails(df.plot, kind='line', blarg=True)

        df = DataFrame(np.random.rand(10, 3),
                       index=list(string.ascii_letters[:10]))
        _check_plot_works(df.plot, use_index=True)
        _check_plot_works(df.plot, sort_columns=False)
        _check_plot_works(df.plot, yticks=[1, 5, 10])
        _check_plot_works(df.plot, xticks=[1, 5, 10])
        _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
        _check_plot_works(df.plot, subplots=True, title='blah')
        _check_plot_works(df.plot, title='blah')

        tuples = zip(list(string.ascii_letters[:10]), range(10))
        df = DataFrame(np.random.rand(10, 3),
                       index=MultiIndex.from_tuples(tuples))
        _check_plot_works(df.plot, use_index=True)

        # unicode
        index = MultiIndex.from_tuples([(u'\u03b1', 0),
                                        (u'\u03b1', 1),
                                        (u'\u03b2', 2),
                                        (u'\u03b2', 3),
                                        (u'\u03b3', 4),
                                        (u'\u03b3', 5),
                                        (u'\u03b4', 6),
                                        (u'\u03b4', 7)], names=['i0', 'i1'])
        columns = MultiIndex.from_tuples([('bar', u'\u0394'),
                                        ('bar', u'\u0395')], names=['c0', 'c1'])
        df = DataFrame(np.random.randint(0, 10, (8, 2)),
                       columns=columns,
                       index=index)
        _check_plot_works(df.plot, title=u'\u03A3')

    @slow
    def test_label(self):
        import matplotlib.pyplot as plt
        plt.close('all')
        df = DataFrame(np.random.randn(10, 3), columns=['a', 'b', 'c'])
        ax = df.plot(x='a', y='b')
        self.assert_(ax.xaxis.get_label().get_text() == 'a')

        plt.close('all')
        ax = df.plot(x='a', y='b', label='LABEL')
        self.assert_(ax.xaxis.get_label().get_text() == 'LABEL')

    @slow
    def test_plot_xy(self):
        import matplotlib.pyplot as plt
        # columns.inferred_type == 'string'
        df = tm.makeTimeDataFrame()
        self._check_data(df.plot(x=0, y=1),
                         df.set_index('A')['B'].plot())
        self._check_data(df.plot(x=0), df.set_index('A').plot())
        self._check_data(df.plot(y=0), df.B.plot())
        self._check_data(df.plot(x='A', y='B'),
                         df.set_index('A').B.plot())
        self._check_data(df.plot(x='A'), df.set_index('A').plot())
        self._check_data(df.plot(y='B'), df.B.plot())

        # columns.inferred_type == 'integer'
        df.columns = range(1, len(df.columns) + 1)
        self._check_data(df.plot(x=1, y=2),
                         df.set_index(1)[2].plot())
        self._check_data(df.plot(x=1), df.set_index(1).plot())
        self._check_data(df.plot(y=1), df[1].plot())

        # figsize and title
        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())

        # columns.inferred_type == 'mixed'
        # TODO add MultiIndex test

    @slow
    def test_xcompat(self):
        import pandas as pd
        import matplotlib.pyplot as plt

        df = tm.makeTimeDataFrame()
        ax = df.plot(x_compat=True)
        lines = ax.get_lines()
        self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        pd.plot_params['xaxis.compat'] = True
        ax = df.plot()
        lines = ax.get_lines()
        self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        pd.plot_params['x_compat'] = False
        ax = df.plot()
        lines = ax.get_lines()
        self.assert_(isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        # useful if you're plotting a bunch together
        with pd.plot_params.use('x_compat', True):
            ax = df.plot()
            lines = ax.get_lines()
            self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        ax = df.plot()
        lines = ax.get_lines()
        self.assert_(isinstance(lines[0].get_xdata(), PeriodIndex))

    @slow
    def test_unsorted_index(self):
        df = DataFrame({'y': range(100)},
                       index=range(99, -1, -1))
        ax = df.plot()
        l = ax.get_lines()[0]
        rs = l.get_xydata()
        rs = Series(rs[:, 1], rs[:, 0], dtype=int)
        tm.assert_series_equal(rs, df.y)

    def _check_data(self, xp, rs):
        xp_lines = xp.get_lines()<commit_msg>TST: avoid platform dependency, close #2854<commit_after>import nose
import os
import string
import unittest

from datetime import datetime, date

from pandas import Series, DataFrame, MultiIndex, PeriodIndex, date_range
import pandas.util.testing as tm

import numpy as np

from numpy.testing import assert_array_equal
from numpy.testing.decorators import slow
import pandas.tools.plotting as plotting


def _skip_if_no_scipy():
    try:
        import scipy
    except ImportError:
        raise nose.SkipTest


class TestSeriesPlots(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        import sys

        # if 'IPython' in sys.modules:
        #     raise nose.SkipTest

        try:
            import matplotlib as mpl
            mpl.use('Agg', warn=False)
        except ImportError:
            raise nose.SkipTest

    def setUp(self):
        self.ts = tm.makeTimeSeries()
        self.ts.name = 'ts'

        self.series = tm.makeStringSeries()
        self.series.name = 'series'

        self.iseries = tm.makePeriodSeries()
        self.iseries.name = 'iseries'

    @slow
    def test_plot(self):
        _check_plot_works(self.ts.plot, label='foo')
        _check_plot_works(self.ts.plot, use_index=False)
        _check_plot_works(self.ts.plot, rot=0)
        _check_plot_works(self.ts.plot, style='.', logy=True)
        _check_plot_works(self.ts.plot, style='.', logx=True)
        _check_plot_works(self.ts.plot, style='.', loglog=True)
        _check_plot_works(self.ts[:10].plot, kind='bar')
        _check_plot_works(self.series[:5].plot, kind='bar')
        _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(np.random.randn(10)).plot(kind='bar', color='black')

    @slow
    def test_bar_colors(self):
        import matplotlib.pyplot as plt
        import matplotlib.colors as colors

        default_colors = 'brgyk'
        custom_colors = 'rgcby'

        plt.close('all')
        df = DataFrame(np.random.randn(5, 5))
        ax = df.plot(kind='bar')

        rects = ax.patches

        conv = colors.colorConverter
        for i, rect in enumerate(rects[::5]):
            xp = conv.to_rgba(default_colors[i])
            rs = rect.get_facecolor()
            self.assert_(xp == rs)

        plt.close('all')

        ax = df.plot(kind='bar', color=custom_colors)

        rects = ax.patches

        conv = colors.colorConverter
        for i, rect in enumerate(rects[::5]):
            xp = conv.to_rgba(custom_colors[i])
            rs = rect.get_facecolor()
            self.assert_(xp == rs)

        plt.close('all')
        df.ix[:, [0]].plot(kind='bar', color='DodgerBlue')

    @slow
    def test_bar_linewidth(self):
        df = DataFrame(np.random.randn(5, 5))

        # regular
        ax = df.plot(kind='bar', linewidth=2)
        for r in ax.patches:
            self.assert_(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)

        # 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)

    @slow
    def test_rotation(self):
        df = DataFrame(np.random.randn(5, 5))
        ax = df.plot(rot=30)
        for l in ax.get_xticklabels():
            self.assert_(l.get_rotation() == 30)

    @slow
    def test_irregular_datetime(self):
        rng = date_range('1/1/2000', '3/1/2000')
        rng = rng[[0, 1, 2, 3, 5, 9, 10, 11, 12]]
        ser = Series(np.random.randn(len(rng)), rng)
        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])

    @slow
    def test_hist(self):
        _check_plot_works(self.ts.hist)
        _check_plot_works(self.ts.hist, grid=False)

        _check_plot_works(self.ts.hist, by=self.ts.index.month)

    @slow
    def test_kde(self):
        _skip_if_no_scipy()
        _check_plot_works(self.ts.plot, kind='kde')
        _check_plot_works(self.ts.plot, kind='density')
        ax = self.ts.plot(kind='kde', logy=True)
        self.assert_(ax.get_yscale() == 'log')

    @slow
    def test_autocorrelation_plot(self):
        from pandas.tools.plotting import autocorrelation_plot
        _check_plot_works(autocorrelation_plot, self.ts)
        _check_plot_works(autocorrelation_plot, self.ts.values)

    @slow
    def test_lag_plot(self):
        from pandas.tools.plotting import lag_plot
        _check_plot_works(lag_plot, self.ts)
        _check_plot_works(lag_plot, self.ts, lag=5)

    @slow
    def test_bootstrap_plot(self):
        from pandas.tools.plotting import bootstrap_plot
        _check_plot_works(bootstrap_plot, self.ts, size=10)


class TestDataFramePlots(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # import sys
        # if 'IPython' in sys.modules:
        #    raise nose.SkipTest

        try:
            import matplotlib as mpl
            mpl.use('Agg', warn=False)
        except ImportError:
            raise nose.SkipTest

    @slow
    def test_plot(self):
        df = tm.makeTimeDataFrame()
        _check_plot_works(df.plot, grid=False)
        _check_plot_works(df.plot, subplots=True)
        _check_plot_works(df.plot, subplots=True, use_index=False)

        df = DataFrame({'x': [1, 2], 'y': [3, 4]})
        self._check_plot_fails(df.plot, kind='line', blarg=True)

        df = DataFrame(np.random.rand(10, 3),
                       index=list(string.ascii_letters[:10]))
        _check_plot_works(df.plot, use_index=True)
        _check_plot_works(df.plot, sort_columns=False)
        _check_plot_works(df.plot, yticks=[1, 5, 10])
        _check_plot_works(df.plot, xticks=[1, 5, 10])
        _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
        _check_plot_works(df.plot, subplots=True, title='blah')
        _check_plot_works(df.plot, title='blah')

        tuples = zip(list(string.ascii_letters[:10]), range(10))
        df = DataFrame(np.random.rand(10, 3),
                       index=MultiIndex.from_tuples(tuples))
        _check_plot_works(df.plot, use_index=True)

        # unicode
        index = MultiIndex.from_tuples([(u'\u03b1', 0),
                                        (u'\u03b1', 1),
                                        (u'\u03b2', 2),
                                        (u'\u03b2', 3),
                                        (u'\u03b3', 4),
                                        (u'\u03b3', 5),
                                        (u'\u03b4', 6),
                                        (u'\u03b4', 7)], names=['i0', 'i1'])
        columns = MultiIndex.from_tuples([('bar', u'\u0394'),
                                        ('bar', u'\u0395')], names=['c0', 'c1'])
        df = DataFrame(np.random.randint(0, 10, (8, 2)),
                       columns=columns,
                       index=index)
        _check_plot_works(df.plot, title=u'\u03A3')

    @slow
    def test_label(self):
        import matplotlib.pyplot as plt
        plt.close('all')
        df = DataFrame(np.random.randn(10, 3), columns=['a', 'b', 'c'])
        ax = df.plot(x='a', y='b')
        self.assert_(ax.xaxis.get_label().get_text() == 'a')

        plt.close('all')
        ax = df.plot(x='a', y='b', label='LABEL')
        self.assert_(ax.xaxis.get_label().get_text() == 'LABEL')

    @slow
    def test_plot_xy(self):
        import matplotlib.pyplot as plt
        # columns.inferred_type == 'string'
        df = tm.makeTimeDataFrame()
        self._check_data(df.plot(x=0, y=1),
                         df.set_index('A')['B'].plot())
        self._check_data(df.plot(x=0), df.set_index('A').plot())
        self._check_data(df.plot(y=0), df.B.plot())
        self._check_data(df.plot(x='A', y='B'),
                         df.set_index('A').B.plot())
        self._check_data(df.plot(x='A'), df.set_index('A').plot())
        self._check_data(df.plot(y='B'), df.B.plot())

        # columns.inferred_type == 'integer'
        df.columns = range(1, len(df.columns) + 1)
        self._check_data(df.plot(x=1, y=2),
                         df.set_index(1)[2].plot())
        self._check_data(df.plot(x=1), df.set_index(1).plot())
        self._check_data(df.plot(y=1), df[1].plot())

        # figsize and title
        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())

        # columns.inferred_type == 'mixed'
        # TODO add MultiIndex test

    @slow
    def test_xcompat(self):
        import pandas as pd
        import matplotlib.pyplot as plt

        df = tm.makeTimeDataFrame()
        ax = df.plot(x_compat=True)
        lines = ax.get_lines()
        self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        pd.plot_params['xaxis.compat'] = True
        ax = df.plot()
        lines = ax.get_lines()
        self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        pd.plot_params['x_compat'] = False
        ax = df.plot()
        lines = ax.get_lines()
        self.assert_(isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        # useful if you're plotting a bunch together
        with pd.plot_params.use('x_compat', True):
            ax = df.plot()
            lines = ax.get_lines()
            self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))

        plt.close('all')
        ax = df.plot()
        lines = ax.get_lines()
        self.assert_(isinstance(lines[0].get_xdata(), PeriodIndex))

    @slow
    def test_unsorted_index(self):
        df = DataFrame({'y': range(100)},
                       index=range(99, -1, -1))
        ax = df.plot()
        l = ax.get_lines()[0]
        rs = l.get_xydata()
        rs = Series(rs[:, 1], rs[:, 0], dtype=np.int64)
        tm.assert_series_equal(rs, df.y)

    def _check_data(self, xp, rs):
        xp_lines = xp.get_lines()
{'fraction_non_alphanumeric': 0.1427120119974844, 'fraction_numerical': 0.01993130472642833, 'mean_word_length': 2.123130382232966, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3283676', 'n_tokens_mistral': 7263, 'n_tokens_neox': 6843, 'n_words': 1226}