Example #1
0
    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")
def fare_analyze(is_plot=True):
    fare_test = titanic_df['Fare']
    print '+' * 40
    print fare_test.head()

    fare_not_survived = titanic_df["Fare"][titanic_df["Survived"] == 0]
    fare_survived = titanic_df["Fare"][titanic_df["Survived"] == 1]

    fare_not_survived = titanic_df['Fare'][titanic_df['Survived'] == 0]
    fare_survived = titanic_df['Fare'][titanic_df['Survived'] == 1]

    # 计算存活和死亡的均值和方差
    avgerage_fare = DataFrame([fare_not_survived.mean(), fare_survived.mean()])
    std_fare = DataFrame([fare_not_survived.std(), fare_survived.std()])

    avgerage_fare = DataFrame([fare_not_survived.mean(), fare_survived.mean()])
    std_fare = DataFrame([fare_not_survived.std(), fare_survived.std()])

    print '-'
    print avgerage_fare
    print std_fare
    # plot
    titanic_df['Fare'].plot(kind='hist', figsize=(15,3), bins=100, xlim=(0,50))

    avgerage_fare.index.names = std_fare.index.names = ["Survived"]

    if is_plot:
        avgerage_fare.plot(yerr=std_fare,kind='bar',legend=False)
Example #3
0
 def test_partially_invalid_plot_data(self):
     kinds = "line", "bar", "barh", "kde", "density"
     df = DataFrame(randn(10, 2), dtype=object)
     df[np.random.rand(df.shape[0]) > 0.5] = "a"
     for kind in kinds:
         with tm.assertRaises(TypeError):
             df.plot(kind=kind)
Example #4
0
def plot_class_distribution(target, ax=None):
    """ Plot the distribution of the classes.

        Parameters
        ----------
        target : array
            The target column of the dataset.

        ax : Matplotlib Axes object
            A matplotlib Axes instance.

        Returns
        -------
        ax : Matplotlib Axes object
            The matplotlib Axes instance where the figure is drawn.
    """

    if not ax:
        ax = plt.gca()

    counts = DataFrame(target).apply(pd.value_counts)
    counts.plot(ax=ax, kind="bar", fontsize=12, legend=False)
    ax.set_xticklabels(labels=counts.index, rotation=0)

    format_thousands = lambda x, pos: format(int(x), ',')
    ax.get_yaxis().set_major_formatter(FuncFormatter(format_thousands))
    ax.grid(False)

    return ax
Example #5
0
def plot_scores(scores, title, x_label, classifier_names):
    """ Make a barplot of the scores of some performance measure.

        Parameters
        ----------
        scores : dict
            Where the keys are the classifier names and the values are the scores.

        title : str
            Title of the plot.

        x_label : str
            Label for the x-axis

        classifier_names : array
            List of the names of the classifiers, the order of which will be used
            to order the bars.
    """

    scores = DataFrame(scores, index=[x_label])
    scores = scores.reindex(columns=classifier_names)

    format_as_percent_plot = lambda x, pos: "{:.0f}%".format(x * 100)
    fig, ax = plt.subplots(figsize=(9, 5))
    scores.plot(ax=ax, kind="bar", title=title, fontsize=12)
    ax.legend(bbox_to_anchor = (1.5, 0.6))
    ax.set_xticklabels([], rotation=0)
    ax.get_yaxis().set_major_formatter(FuncFormatter(format_as_percent_plot))

    plt.show()
Example #6
0
    def test_line_colors(self):
        import matplotlib.pyplot as plt
        import sys
        from StringIO import StringIO

        custom_colors = 'rgcby'

        plt.close('all')
        df = DataFrame(np.random.randn(5, 5))

        ax = df.plot(color=custom_colors)

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = custom_colors[i]
            rs = l.get_color()
            self.assert_(xp == rs)

        tmp = sys.stderr
        sys.stderr = StringIO()
        try:
            plt.close('all')
            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())
        finally:
            sys.stderr = tmp
    def test_from_resampling_area_line_mixed(self):
        idxh = date_range("1/1/1999", periods=52, freq="W")
        idxl = date_range("1/1/1999", periods=12, freq="M")
        high = DataFrame(np.random.rand(len(idxh), 3), index=idxh, columns=[0, 1, 2])
        low = DataFrame(np.random.rand(len(idxl), 3), index=idxl, columns=[0, 1, 2])

        # low to high
        for kind1, kind2 in [("line", "area"), ("area", "line")]:
            ax = low.plot(kind=kind1, stacked=True)
            ax = high.plot(kind=kind2, stacked=True, ax=ax)

            # check low dataframe result
            expected_x = np.array(
                [1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549, 1553, 1558, 1562], dtype=np.float64
            )
            expected_y = np.zeros(len(expected_x), dtype=np.float64)
            for i in range(3):
                l = ax.lines[i]
                self.assertEqual(PeriodIndex(l.get_xdata()).freq, idxh.freq)
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                # check stacked values are correct
                expected_y += low[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)

            # check high dataframe result
            expected_x = idxh.to_period().asi8.astype(np.float64)
            expected_y = np.zeros(len(expected_x), dtype=np.float64)
            for i in range(3):
                l = ax.lines[3 + i]
                self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, idxh.freq)
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                expected_y += high[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)

        # high to low
        for kind1, kind2 in [("line", "area"), ("area", "line")]:
            ax = high.plot(kind=kind1, stacked=True)
            ax = low.plot(kind=kind2, stacked=True, ax=ax)

            # check high dataframe result
            expected_x = idxh.to_period().asi8.astype(np.float64)
            expected_y = np.zeros(len(expected_x), dtype=np.float64)
            for i in range(3):
                l = ax.lines[i]
                self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, idxh.freq)
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                expected_y += high[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)

            # check low dataframe result
            expected_x = np.array(
                [1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549, 1553, 1558, 1562], dtype=np.float64
            )
            expected_y = np.zeros(len(expected_x), dtype=np.float64)
            for i in range(3):
                l = ax.lines[3 + i]
                self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, idxh.freq)
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                expected_y += low[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)
def slide_11():
    fig, axes = plt.subplots(2, 1)
    data = Series(np.random.rand(16), index=list('abcdefghijklmnop'))

    data.plot(kind='bar', ax=axes[0], color='k', alpha=0.7)
    data.plot(kind='barh', ax=axes[1], color='k', alpha=0.7)

    df = DataFrame(np.random.rand(6, 4),
                   index=['one', 'two', 'three', 'four', 'five', 'six'],
                   columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))
    print df
    df.plot(kind='bar')
    df.plot(kind='barh', stacked=True, alpha=0.5)

    tips = pd.read_csv(TIPSCSVPATH)
    print tips.head()
    party_counts = pd.crosstab(index=tips.day, columns=tips.sizes)
    print '曜日とパーティの大きさ別に仕分け'
    print party_counts
    party_counts = party_counts.ix[:, 2: 5]
    print 'サイズ1と6のパーティは少ないから除外'
    print party_counts
    print '正規化'
    party_pcts = party_counts.div(party_counts.sum(1).astype(float), axis=0)
    print party_pcts
    party_pcts.plot(kind='bar', stacked=True)
Example #9
0
    def test_time(self):
        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])
        df = DataFrame({'a': np.random.randn(len(ts)),
                        'b': np.random.randn(len(ts))},
                       index=ts)
        _, ax = self.plt.subplots()
        df.plot(ax=ax)

        # verify tick labels
        ticks = ax.get_xticks()
        labels = ax.get_xticklabels()
        for t, l in zip(ticks, labels):
            m, s = divmod(int(t), 60)
            h, m = divmod(m, 60)
            xp = l.get_text()
            if len(xp) > 0:
                rs = time(h, m, s).strftime('%H:%M:%S')
                assert xp == rs

        # change xlim
        ax.set_xlim('1:30', '5:00')

        # check tick labels again
        ticks = ax.get_xticks()
        labels = ax.get_xticklabels()
        for t, l in zip(ticks, labels):
            m, s = divmod(int(t), 60)
            h, m = divmod(m, 60)
            xp = l.get_text()
            if len(xp) > 0:
                rs = time(h, m, s).strftime('%H:%M:%S')
                assert xp == rs
Example #10
0
    def test_errorbar_plot(self):

        d = {'x': np.arange(12), 'y': np.arange(12, 0, -1)}
        df = DataFrame(d)
        d_err = {'x': np.ones(12)*0.2, 'y': np.ones(12)*0.4}
        df_err = DataFrame(d_err)

        # check line plots
        _check_plot_works(df.plot, yerr=df_err, logy=True)
        _check_plot_works(df.plot, yerr=df_err, logx=True, logy=True)

        kinds = ['line', 'bar', 'barh']
        for kind in kinds:
            _check_plot_works(df.plot, yerr=df_err['x'], kind=kind)
            _check_plot_works(df.plot, yerr=d_err, kind=kind)
            _check_plot_works(df.plot, yerr=df_err, xerr=df_err, kind=kind)
            _check_plot_works(df.plot, yerr=df_err['x'], xerr=df_err['x'], kind=kind)
            _check_plot_works(df.plot, yerr=df_err, xerr=df_err, subplots=True, kind=kind)

        _check_plot_works((df+1).plot, yerr=df_err, xerr=df_err, kind='bar', log=True)

        # yerr is raw error values
        _check_plot_works(df['y'].plot, yerr=np.ones(12)*0.4)
        _check_plot_works(df.plot, yerr=np.ones((2, 12))*0.4)

        # yerr is column name
        df['yerr'] = np.ones(12)*0.2
        _check_plot_works(df.plot, y='y', x='x', yerr='yerr')

        with tm.assertRaises(ValueError):
            df.plot(yerr=np.random.randn(11))

        df_err = DataFrame({'x': ['zzz']*12, 'y': ['zzz']*12})
        with tm.assertRaises(TypeError):
            df.plot(yerr=df_err)
Example #11
0
 def test_fontsize_set_correctly(self):
     # For issue #8765
     df = DataFrame(np.random.randn(10, 9), index=range(10))
     fig, ax = self.plt.subplots()
     df.plot(fontsize=2, ax=ax)
     for label in (ax.get_xticklabels() + ax.get_yticklabels()):
         assert label.get_fontsize() == 2
Example #12
0
    def test_from_resampling_area_line_mixed(self):
        idxh = date_range('1/1/1999', periods=52, freq='W')
        idxl = date_range('1/1/1999', periods=12, freq='M')
        high = DataFrame(np.random.rand(len(idxh), 3),
                         index=idxh, columns=[0, 1, 2])
        low = DataFrame(np.random.rand(len(idxl), 3),
                     index=idxl, columns=[0, 1, 2])

        # low to high
        for kind1, kind2 in [('line', 'area'), ('area', 'line')]:
            ax = low.plot(kind=kind1, stacked=True)
            ax = high.plot(kind=kind2, stacked=True, ax=ax)

            # check low dataframe result
            expected_x = np.array([1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549,
                                   1553, 1558, 1562])
            expected_y = np.zeros(len(expected_x))
            for i in range(3):
                l = ax.lines[i]
                self.assertTrue(PeriodIndex(data=l.get_xdata()).freq.startswith('W'))
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                # check stacked values are correct
                expected_y += low[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)

            # check high dataframe result
            expected_x = idxh.to_period().asi8
            expected_y = np.zeros(len(expected_x))
            for i in range(3):
                l = ax.lines[3 + i]
                self.assertTrue(PeriodIndex(data=l.get_xdata()).freq.startswith('W'))
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                expected_y += high[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)

        # high to low
        for kind1, kind2 in [('line', 'area'), ('area', 'line')]:
            ax = high.plot(kind=kind1, stacked=True)
            ax = low.plot(kind=kind2, stacked=True, ax=ax)

            # check high dataframe result
            expected_x = idxh.to_period().asi8
            expected_y = np.zeros(len(expected_x))
            for i in range(3):
                l = ax.lines[i]
                self.assertTrue(PeriodIndex(data=l.get_xdata()).freq.startswith('W'))
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                expected_y += high[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)

            # check low dataframe result
            expected_x = np.array([1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549,
                                   1553, 1558, 1562])
            expected_y = np.zeros(len(expected_x))
            for i in range(3):
                l = ax.lines[3 + i]
                self.assertTrue(PeriodIndex(data=l.get_xdata()).freq.startswith('W'))
                self.assert_numpy_array_equal(l.get_xdata(orig=False), expected_x)
                expected_y += low[i].values
                self.assert_numpy_array_equal(l.get_ydata(orig=False), expected_y)
Example #13
0
	def plot_call_summary(self):
		""" """
		# Gets the most expensive 1000 calls
		top_n_expensive_calls = self.df.sort_index(by='elapsed', ascending=False)[:1000]
		calls = [ call  for call, group in top_n_expensive_calls.groupby('call') ]

		data = []
		for call in calls:
			call_info = self.df[self.df['call']==call]['elapsed']
			call_data = {}
			call_data['call'] = call
			call_data['mean'] = call_info.mean()
			call_data['count'] = call_info.count()
			call_data['max'] = call_info.max()
			call_data['min'] = call_info.min()
			data.append(call_data)

		call_data_df = DataFrame(data)

		fig = plt.figure()
		fig.suptitle('{0}   -   {1}'.format(self.min_timestamp, self.max_timestamp), fontsize=16)

		ax = fig.add_subplot(3, 1, 1)
		#ax.get_xaxis().set_visible(False)
		self.df[self.df['elapsed']>=5].sort_index(by='timestamp').plot(title='Response time > 5 seconds', ax=ax, x='timestamp', y='elapsed')

		ax = fig.add_subplot(3, 1, 2)
		call_data_df[['call', 'min', 'max', 'mean']].set_index('call').plot(title='Response Time', ax=ax, kind='barh')

		ax = fig.add_subplot(3, 1, 3)
		call_data_df.plot(title='Call Count', ax=ax, x='call', y='count', kind='barh')

		fig.show()

		self.plot_calls_distribution(calls)
Example #14
0
    def test_line_colors(self):
        import matplotlib.pyplot as plt
        import sys
        from StringIO import StringIO

        custom_colors = 'rgcby'

        plt.close('all')
        df = DataFrame(np.random.randn(5, 5))

        ax = df.plot(color=custom_colors)

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = custom_colors[i]
            rs = l.get_color()
            self.assert_(xp == rs)

        tmp = sys.stderr
        sys.stderr = StringIO()
        try:
            plt.close('all')
            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())
        finally:
            sys.stderr = tmp

        # make color a list if plotting one column frame
        # handles cases like df.plot(color='DodgerBlue')
        plt.close('all')
        df.ix[:, [0]].plot(color='DodgerBlue')
Example #15
0
    def test_bar_colors(self):
        import matplotlib.pyplot as plt
        import matplotlib.colors as colors

        default_colors = plt.rcParams.get('axes.color_cycle')
        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 % len(default_colors)])
            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')
class BJWorksAverageWage():

    def __init__(self):
        self.url = 'http://www.bjrbj.gov.cn/bmfw/ywml/201601/t20160112_55858.html'
        self.wagelist = DataFrame(columns=['wage'])

    def crawl(self):
        r = requests.get(self.url)
        html = etree.HTML(r.text)
        tbody = html.xpath('//*/tbody')[0]
        for i, tr in enumerate(tbody):
            if i == 0:
                pass
            elif i == 1:
                year = datetime.strptime(tr[0][0].text,'%Y')
                wage = float(tr[1][0].text)
                self.wagelist.loc[year] = [wage]
            else:
                year = datetime.strptime(tr[0][0][0].text,'%Y')
                wage = float(tr[1][0][0].text)
                self.wagelist.loc[year] = [wage]

    def save(self):
        pass

    def plot(self):
        import matplotlib.pyplot as plt
        plt.figure()
        self.wagelist.plot()
Example #17
0
    def test_subplots(self):
        df = DataFrame(np.random.rand(10, 3),
                       index=list(string.ascii_letters[:10]))

        axes = df.plot(subplots=True, sharex=True, legend=True)

        for ax in axes:
            self.assert_(ax.get_legend() is not None)

        axes = df.plot(subplots=True, sharex=True)
        for ax in axes[:-2]:
            [self.assert_(not label.get_visible())
             for label in ax.get_xticklabels()]
            [self.assert_(label.get_visible())
             for label in ax.get_yticklabels()]

        [self.assert_(label.get_visible())
         for label in axes[-1].get_xticklabels()]
        [self.assert_(label.get_visible())
         for label in axes[-1].get_yticklabels()]

        axes = df.plot(subplots=True, sharex=False)
        for ax in axes:
            [self.assert_(label.get_visible())
             for label in ax.get_xticklabels()]
            [self.assert_(label.get_visible())
             for label in ax.get_yticklabels()]
Example #18
0
 def test_partially_invalid_plot_data(self):
     kinds = 'line', 'bar', 'barh', 'kde', 'density'
     df = DataFrame(randn(10, 2), dtype=object)
     df[np.random.rand(df.shape[0]) > 0.5] = 'a'
     for kind in kinds:
         with tm.assertRaises(TypeError):
             df.plot(kind=kind)
Example #19
0
    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)
Example #20
0
    def test_bar_colors(self):
        import matplotlib.pyplot as plt
        import matplotlib.colors as colors

        default_colors = plt.rcParams.get('axes.color_cycle')
        custom_colors = 'rgcby'

        df = DataFrame(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 % len(default_colors)])
            rs = rect.get_facecolor()
            self.assertEqual(xp, rs)

        tm.close()

        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.assertEqual(xp, rs)

        tm.close()
        from matplotlib import cm

        # Test str -> colormap functionality
        ax = df.plot(kind='bar', colormap='jet')

        rects = ax.patches

        rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5))
        for i, rect in enumerate(rects[::5]):
            xp = rgba_colors[i]
            rs = rect.get_facecolor()
            self.assertEqual(xp, rs)

        tm.close()

        # Test colormap functionality
        ax = df.plot(kind='bar', colormap=cm.jet)

        rects = ax.patches

        rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5))
        for i, rect in enumerate(rects[::5]):
            xp = rgba_colors[i]
            rs = rect.get_facecolor()
            self.assertEqual(xp, rs)

        tm.close()
        df.ix[:, [0]].plot(kind='bar', color='DodgerBlue')
Example #21
0
    def test_rotation(self):
        df = DataFrame(randn(5, 5))
        # Default rot 0
        axes = df.plot()
        self._check_ticks_props(axes, xrot=0)

        axes = df.plot(rot=30)
        self._check_ticks_props(axes, xrot=30)
Example #22
0
    def test_line_colors(self):
        import matplotlib.pyplot as plt
        import sys
        from StringIO import StringIO
        from matplotlib import cm

        custom_colors = "rgcby"

        plt.close("all")
        df = DataFrame(np.random.randn(5, 5))

        ax = df.plot(color=custom_colors)

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = custom_colors[i]
            rs = l.get_color()
            self.assert_(xp == rs)

        tmp = sys.stderr
        sys.stderr = StringIO()
        try:
            plt.close("all")
            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())
        finally:
            sys.stderr = tmp

        plt.close("all")

        ax = df.plot(colormap="jet")

        rgba_colors = map(cm.jet, np.linspace(0, 1, len(df)))

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = rgba_colors[i]
            rs = l.get_color()
            self.assert_(xp == rs)

        plt.close("all")

        ax = df.plot(colormap=cm.jet)

        rgba_colors = map(cm.jet, np.linspace(0, 1, len(df)))

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = rgba_colors[i]
            rs = l.get_color()
            self.assert_(xp == rs)

        # make color a list if plotting one column frame
        # handles cases like df.plot(color='DodgerBlue')
        plt.close("all")
        df.ix[:, [0]].plot(color="DodgerBlue")
Example #23
0
    def test_df_series_secondary_legend(self):
        # GH 9779
        df = DataFrame(np.random.randn(30, 3), columns=list('abc'))
        s = Series(np.random.randn(30), name='x')

        # primary -> secondary (without passing ax)
        ax = df.plot()
        s.plot(legend=True, secondary_y=True)
        # both legends are dran on left ax
        # left and right axis must be visible
        self._check_legend_labels(ax, labels=['a', 'b', 'c', 'x (right)'])
        self.assertTrue(ax.get_yaxis().get_visible())
        self.assertTrue(ax.right_ax.get_yaxis().get_visible())
        tm.close()

        # primary -> secondary (with passing ax)
        ax = df.plot()
        s.plot(ax=ax, legend=True, secondary_y=True)
        # both legends are dran on left ax
        # left and right axis must be visible
        self._check_legend_labels(ax, labels=['a', 'b', 'c', 'x (right)'])
        self.assertTrue(ax.get_yaxis().get_visible())
        self.assertTrue(ax.right_ax.get_yaxis().get_visible())
        tm.close()

        # seconcary -> secondary (without passing ax)
        ax = df.plot(secondary_y=True)
        s.plot(legend=True, secondary_y=True)
        # both legends are dran on left ax
        # left axis must be invisible and right axis must be visible
        expected = ['a (right)', 'b (right)', 'c (right)', 'x (right)']
        self._check_legend_labels(ax.left_ax, labels=expected)
        self.assertFalse(ax.left_ax.get_yaxis().get_visible())
        self.assertTrue(ax.get_yaxis().get_visible())
        tm.close()

        # secondary -> secondary (with passing ax)
        ax = df.plot(secondary_y=True)
        s.plot(ax=ax, legend=True, secondary_y=True)
        # both legends are dran on left ax
        # left axis must be invisible and right axis must be visible
        expected = ['a (right)', 'b (right)', 'c (right)', 'x (right)']
        self._check_legend_labels(ax.left_ax, expected)
        self.assertFalse(ax.left_ax.get_yaxis().get_visible())
        self.assertTrue(ax.get_yaxis().get_visible())
        tm.close()

        # secondary -> secondary (with passing ax)
        ax = df.plot(secondary_y=True, mark_right=False)
        s.plot(ax=ax, legend=True, secondary_y=True)
        # both legends are dran on left ax
        # left axis must be invisible and right axis must be visible
        expected = ['a', 'b', 'c', 'x (right)']
        self._check_legend_labels(ax.left_ax, expected)
        self.assertFalse(ax.left_ax.get_yaxis().get_visible())
        self.assertTrue(ax.get_yaxis().get_visible())
        tm.close()
def slide_10():
    s = Series(randn(10).cumsum(), index=np.arange(0, 100, 10))
    print s
    s.plot()

    df = DataFrame(randn(10, 4).cumsum(0),
                   columns=['A', 'B', 'C', 'D'],
                   index=np.arange(0, 100, 10))
    df.plot()
Example #25
0
 def test_nonzero_base(self):
     # GH2571
     idx = (date_range('2012-12-20', periods=24, freq='H') + timedelta(
         minutes=30))
     df = DataFrame(np.arange(24), index=idx)
     _, ax = self.plt.subplots()
     df.plot(ax=ax)
     rs = ax.get_lines()[0].get_xdata()
     assert not Index(rs).is_normalized
Example #26
0
    def test_line_colors(self):
        import matplotlib.pyplot as plt
        import sys
        from matplotlib import cm

        custom_colors = 'rgcby'

        df = DataFrame(randn(5, 5))

        ax = df.plot(color=custom_colors)

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = custom_colors[i]
            rs = l.get_color()
            self.assertEqual(xp, rs)

        tmp = sys.stderr
        sys.stderr = StringIO()
        try:
            tm.close()
            ax2 = df.plot(colors=custom_colors)
            lines2 = ax2.get_lines()
            for l1, l2 in zip(lines, lines2):
                self.assertEqual(l1.get_color(), l2.get_color())
        finally:
            sys.stderr = tmp

        tm.close()

        ax = df.plot(colormap='jet')

        rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df)))

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = rgba_colors[i]
            rs = l.get_color()
            self.assertEqual(xp, rs)

        tm.close()

        ax = df.plot(colormap=cm.jet)

        rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df)))

        lines = ax.get_lines()
        for i, l in enumerate(lines):
            xp = rgba_colors[i]
            rs = l.get_color()
            self.assertEqual(xp, rs)

        # make color a list if plotting one column frame
        # handles cases like df.plot(color='DodgerBlue')
        tm.close()
        df.ix[:, [0]].plot(color='DodgerBlue')
Example #27
0
    def test_rotation(self):
        df = DataFrame(randn(5, 5))
        # Default rot 0
        _, ax = self.plt.subplots()
        axes = df.plot(ax=ax)
        self._check_ticks_props(axes, xrot=0)

        _, ax = self.plt.subplots()
        axes = df.plot(rot=30, ax=ax)
        self._check_ticks_props(axes, xrot=30)
Example #28
0
    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')
Example #29
0
 def test_kde(self):
     _skip_if_no_scipy()
     df = DataFrame(randn(100, 4))
     _check_plot_works(df.plot, kind='kde')
     _check_plot_works(df.plot, kind='kde', subplots=True)
     ax = df.plot(kind='kde')
     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')
Example #30
0
    def test_nonnumeric_exclude(self):
        idx = date_range('1/1/1987', freq='A', periods=3)
        df = DataFrame({'A': ["x", "y", "z"], 'B': [1, 2, 3]}, idx)

        fig, ax = self.plt.subplots()
        df.plot(ax=ax)  # it works
        assert len(ax.get_lines()) == 1  # B was plotted
        self.plt.close(fig)

        pytest.raises(TypeError, df['A'].plot)