Skip to content

API & BUG: allow list-like y argument to df.plot & fix integer arg to x,y #20000

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 22, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,7 @@ Plotting
^^^^^^^^

- :func:`DataFrame.plot` now raises a ``ValueError`` when the ``x`` or ``y`` argument is improperly formed (:issue:`18671`)
- :func:`DataFrame.plot` now supports multiple columns to the ``y`` argument (:issue:`19699`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this first should be on Other Enhancements section

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you move this to other enhancements?

- Bug in formatting tick labels with ``datetime.time()`` and fractional seconds (:issue:`18478`).
- :meth:`Series.plot.kde` has exposed the args ``ind`` and ``bw_method`` in the docstring (:issue:`18461`). The argument ``ind`` may now also be an integer (number of sample points).

Expand Down
31 changes: 23 additions & 8 deletions pandas/plotting/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1714,13 +1714,28 @@ def _plot(data, x=None, y=None, subplots=False,
data = data.set_index(x)

if y is not None:
if is_integer(y) and not data.columns.holds_integer():
int_cols = is_integer(y) or any(is_integer(col) for col in y)
if int_cols and not data.columns.holds_integer():
y = data.columns[y]
elif not isinstance(data[y], ABCSeries):
raise ValueError("y must be a label or position")
label = kwds['label'] if 'label' in kwds else y
series = data[y].copy() # Don't modify
series.name = label
elif not isinstance(data[y], (ABCSeries, ABCDataFrame)):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where is the test for this? (as you expanded to both Series & DataFrame)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point, removing

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are you actually selecting data[y] here what else could data[y] be?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this can probably be removed / replaced?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed, will remove

raise ValueError(
"y must be a label or position or list of them"
)

label_kw = kwds['label'] if 'label' in kwds else False
new_data = data[y].copy() # Don't modify

if isinstance(data[y], ABCSeries):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can just test if y is_scalar

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate column names may mess that up, not sure if we allow that here though.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate column names may mess that up

right, that's why I have the check for ABCSeries

label_name = label_kw or y
new_data.name = label_name
else:
match = is_list_like(label_kw) and len(label_kw) == len(y)
if label_kw and not match:
raise ValueError(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test that raises this assertion?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where is this test?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"label should be list-like and same length as y"
)
label_name = label_kw or data[y].columns
new_data.columns = label_name

for kw in ['xerr', 'yerr']:
if (kw in kwds) and \
Expand All @@ -1730,7 +1745,7 @@ def _plot(data, x=None, y=None, subplots=False,
kwds[kw] = data[kwds[kw]]
except (IndexError, KeyError, TypeError):
pass
data = series
data = new_data
plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)

plot_obj.generate()
Expand All @@ -1743,7 +1758,7 @@ def _plot(data, x=None, y=None, subplots=False,
series_kind = ""

df_coord = """x : label or position, default None
y : label or position, default None
y : label, position or list of label, positions, default None
Allows plotting of one column versus another"""
series_coord = ""

Expand Down
17 changes: 13 additions & 4 deletions pandas/tests/plotting/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2172,24 +2172,33 @@ def test_invalid_kind(self):

@pytest.mark.parametrize("x,y", [
(['B', 'C'], 'A'),
('A', ['B', 'C'])
(['A'], ['B', 'C'])
])
def test_invalid_xy_args(self, x, y):
# GH 18671
# GH 18671, 19699 allows y to be list-like but not x
df = DataFrame({"A": [1, 2], 'B': [3, 4], 'C': [5, 6]})
with pytest.raises(ValueError):
df.plot(x=x, y=y)

@pytest.mark.parametrize("x,y", [
('A', 'B'),
('B', 'A')
(['A'], 'B')
])
def test_invalid_xy_args_dup_cols(self, x, y):
# GH 18671
# GH 18671, 19699 allows y to be list-like but not x
df = DataFrame([[1, 3, 5], [2, 4, 6]], columns=list('AAB'))
with pytest.raises(ValueError):
df.plot(x=x, y=y)

@pytest.mark.parametrize("y,lbl", [
(['B'], ['b']),
(['B', 'C'], ['b', 'c'])
])
def test_y_listlike(self, y, lbl):
# GH 19699
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you give a 1-liner expln

df = DataFrame({"A": [1, 2], 'B': [3, 4], 'C': [5, 6]})
_check_plot_works(df.plot, x='A', y=y, label=lbl)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you get the ax from df.plot and assert that it has two lines? I think len(ax.lines) should work.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also check the color. What happens? Ideally it's the same as df.set_index('x').plot(), so two different colors.


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add tests for

  1. all integer columns: x=0, y=[1, 2]
  2. Mix of int and named columns. x=0, y=['A', 2]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mix of int and named columns. x=0, y=['A', 2]

Good point. Shouldn't this raise tho? If you try this on a DataFrame you'll get a KeyError. IMO we shouldn't allow users to specify a mix of int & named cols since it's unclear what you actually want.

@pytest.mark.slow
def test_hexbin_basic(self):
df = self.hexbin_df
Expand Down