From 385ce232aed7da6f9c142e8edc694d772b5f453f Mon Sep 17 00:00:00 2001 From: "xxx.Yan" Date: Thu, 22 Aug 2024 23:19:37 +0800 Subject: [PATCH] BUG: Fix Ability to set both color and style in pandas plotting (#59574) * BUG: Fix plotting set color style dict sametime * BUG: chore pre-commit inconsistent-namespace-usage * BUG: Chore Conditional block * Update doc/source/whatsnew/v3.0.0.rst Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com> * BUG: Chore pre-commit sort whatsnew entries alphabetically --------- Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com> --- doc/source/whatsnew/v3.0.0.rst | 1 + pandas/plotting/_matplotlib/core.py | 4 +++- pandas/tests/plotting/frame/test_frame_color.py | 12 ++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index e56f3ffc01e85..b6cb3f55869b1 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -632,6 +632,7 @@ Period Plotting ^^^^^^^^ - Bug in :meth:`.DataFrameGroupBy.boxplot` failed when there were multiple groupings (:issue:`14701`) +- Bug in :meth:`DataFrame.plot.line` raising ``ValueError`` when set both color and a ``dict`` style (:issue:`59461`) - Bug in :meth:`DataFrame.plot` that causes a shift to the right when the frequency multiplier is greater than one. (:issue:`57587`) - Bug in :meth:`Series.plot` with ``kind="pie"`` with :class:`ArrowDtype` (:issue:`59192`) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 9a7e563332a42..ed24e246c5079 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -451,7 +451,9 @@ def _validate_color_args(self, color, colormap): ) if self.style is not None: - if is_list_like(self.style): + if isinstance(self.style, dict): + styles = [self.style[col] for col in self.columns if col in self.style] + elif is_list_like(self.style): styles = self.style else: styles = [self.style] diff --git a/pandas/tests/plotting/frame/test_frame_color.py b/pandas/tests/plotting/frame/test_frame_color.py index 4b35e896e1a6c..ce198fbff1185 100644 --- a/pandas/tests/plotting/frame/test_frame_color.py +++ b/pandas/tests/plotting/frame/test_frame_color.py @@ -95,6 +95,18 @@ def test_color_and_marker(self, color, expected): assert all(i.get_linestyle() == "--" for i in ax.lines) assert all(i.get_marker() == "d" for i in ax.lines) + def test_color_and_style(self): + color = {"g": "black", "h": "brown"} + style = {"g": "-", "h": "--"} + expected_color = ["black", "brown"] + expected_style = ["-", "--"] + df = DataFrame({"g": [1, 2], "h": [2, 3]}, index=[1, 2]) + ax = df.plot.line(color=color, style=style) + color = [i.get_color() for i in ax.lines] + style = [i.get_linestyle() for i in ax.lines] + assert color == expected_color + assert style == expected_style + def test_bar_colors(self): default_colors = _unpack_cycler(plt.rcParams)