diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt index 3c3742c968642..c874a9aaa5d93 100644 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -50,6 +50,8 @@ Performance Improvements Bug Fixes ~~~~~~~~~ +- Fixed bug (:issue:`9542`) where labels did not appear properly in legend of ``DataFrame.plot()``. Passing ``label=`` args also now works, and series indices are no longer mutated. + diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 1cb11179b2430..b5d2b91aed1b1 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -1064,12 +1064,6 @@ def test_implicit_label(self): ax = df.plot(x='a', y='b') self._check_text_labels(ax.xaxis.get_label(), 'a') - @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._check_text_labels(ax.xaxis.get_label(), 'LABEL') - @slow def test_donot_overwrite_index_name(self): # GH 8494 @@ -2542,6 +2536,20 @@ def test_df_legend_labels(self): ax = df3.plot(kind='scatter', x='g', y='h', label='data3', ax=ax) self._check_legend_labels(ax, labels=['data1', 'data3']) + # ensure label args pass through and + # index name does not mutate + # column names don't mutate + df5 = df.set_index('a') + ax = df5.plot(y='b') + self._check_legend_labels(ax, labels=['b']) + ax = df5.plot(y='b', label='LABEL_b') + self._check_legend_labels(ax, labels=['LABEL_b']) + self._check_text_labels(ax.xaxis.get_label(), 'a') + ax = df5.plot(y='c', label='LABEL_c', ax=ax) + self._check_legend_labels(ax, labels=['LABEL_b','LABEL_c']) + self.assertTrue(df5.columns.tolist() == ['b','c']) + + def test_legend_name(self): multi = DataFrame(randn(4, 4), columns=[np.array(['a', 'a', 'b', 'b']), diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index cf9c890823f8f..55b21c4b75fa0 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -886,10 +886,11 @@ def _iter_data(self, data=None, keep_index=False, fillna=None): from pandas.core.frame import DataFrame if isinstance(data, (Series, np.ndarray, Index)): + label = self.label if self.label is not None else data.name if keep_index is True: - yield self.label, data + yield label, data else: - yield self.label, np.asarray(data) + yield label, np.asarray(data) elif isinstance(data, DataFrame): if self.sort_columns: columns = com._try_sort(data.columns) @@ -2306,10 +2307,9 @@ def _plot(data, x=None, y=None, subplots=False, if y is not None: if com.is_integer(y) and not data.columns.holds_integer(): y = data.columns[y] - label = x if x is not None else data.index.name - label = kwds.pop('label', label) + label = kwds['label'] if 'label' in kwds else y series = data[y].copy() # Don't modify - series.index.name = label + series.name = label for kw in ['xerr', 'yerr']: if (kw in kwds) and \