diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index e00b177f2a2fc..5abad99637ebe 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -664,6 +664,7 @@ Plotting - Bug in :meth:`Series.plot` and :meth:`DataFrame.plot` was throwing :exc:`ValueError` with a :class:`Series` or :class:`DataFrame` indexed by a :class:`TimedeltaIndex` with a fixed frequency when x-axis lower limit was greater than upper limit (:issue:`37454`) - Bug in :meth:`DataFrameGroupBy.boxplot` when ``subplots=False``, a KeyError would raise (:issue:`16748`) +- Bug in :meth:`DataFrame.plot` and :meth:`Series.plot` was overwriting matplotlib's shared y axes behaviour when no sharey parameter was passed (:issue:`37942`) Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 2501d84de4459..97fa3f11e9dfb 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1338,7 +1338,9 @@ def _plot( def _post_plot_logic(self, ax: "Axes", data): LinePlot._post_plot_logic(self, ax, data) - if self.ylim is None: + is_shared_y = len(list(ax.get_shared_y_axes())) > 0 + # do not override the default axis behaviour in case of shared y axes + if self.ylim is None and not is_shared_y: if (data >= 0).all().all(): ax.set_ylim(0, None) elif (data <= 0).all().all(): diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index 3c43e0b693a1b..56ac7a477adbb 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -477,6 +477,17 @@ def test_area_lim(self): ymin, ymax = ax.get_ylim() assert ymax == 0 + def test_area_sharey_dont_overwrite(self): + # GH37942 + df = DataFrame(np.random.rand(4, 2), columns=["x", "y"]) + fig, (ax1, ax2) = self.plt.subplots(1, 2, sharey=True) + + df.plot(ax=ax1, kind="area") + df.plot(ax=ax2, kind="area") + + assert ax1._shared_y_axes.joined(ax1, ax2) + assert ax2._shared_y_axes.joined(ax1, ax2) + @pytest.mark.slow def test_bar_linewidth(self): df = DataFrame(np.random.randn(5, 5)) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index f3289d0573de2..b8dd2ada87506 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -140,6 +140,16 @@ def test_ts_area_lim(self): assert xmax >= line[-1] self._check_ticks_props(ax, xrot=0) + def test_area_sharey_dont_overwrite(self): + # GH37942 + fig, (ax1, ax2) = self.plt.subplots(1, 2, sharey=True) + + abs(self.ts).plot(ax=ax1, kind="area") + abs(self.ts).plot(ax=ax2, kind="area") + + assert ax1._shared_y_axes.joined(ax1, ax2) + assert ax2._shared_y_axes.joined(ax1, ax2) + def test_label(self): s = Series([1, 2]) _, ax = self.plt.subplots()