Skip to content

ENH: Fix support for matplotlib's constrained_layout (#25261) #39394

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
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ Plotting
^^^^^^^^

- Bug in :func:`scatter_matrix` raising when 2d ``ax`` argument passed (:issue:`16253`)
-
- Support matplotlib's ``constrained_layout=True`` (:issue:`25261`)
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 be slightly more verbose here. this allows passing this option right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The change just prevents pandas from doing incompatible things when a figure has constrained_layout enabled.

-

Groupby/resample/rolling
Expand Down
10 changes: 7 additions & 3 deletions pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@
from pandas.io.formats.printing import pprint_thing
from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
from pandas.plotting._matplotlib.style import get_standard_colors
from pandas.plotting._matplotlib.tools import create_subplots, flatten_axes
from pandas.plotting._matplotlib.tools import (
create_subplots,
flatten_axes,
maybe_adjust_figure,
)

if TYPE_CHECKING:
from matplotlib.axes import Axes
Expand Down Expand Up @@ -229,7 +233,7 @@ def _grouped_plot_by_column(

byline = by[0] if len(by) == 1 else by
fig.suptitle(f"Boxplot grouped by {byline}")
fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)

return result

Expand Down Expand Up @@ -436,7 +440,7 @@ def boxplot_frame_groupby(
)
ax.set_title(pprint_thing(key))
ret.loc[key] = d
fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
else:
keys, frames = zip(*grouped)
if grouped.axis == 0:
Expand Down
7 changes: 4 additions & 3 deletions pandas/plotting/_matplotlib/hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pandas.plotting._matplotlib.tools import (
create_subplots,
flatten_axes,
maybe_adjust_figure,
set_ticks_props,
)

Expand Down Expand Up @@ -296,8 +297,8 @@ def plot_group(group, ax):
axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot
)

fig.subplots_adjust(
bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3
maybe_adjust_figure(
fig, bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3
)
return axes

Expand Down Expand Up @@ -456,6 +457,6 @@ def hist_frame(
set_ticks_props(
axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot
)
fig.subplots_adjust(wspace=0.3, hspace=0.3)
maybe_adjust_figure(fig, wspace=0.3, hspace=0.3)

return axes
12 changes: 9 additions & 3 deletions pandas/plotting/_matplotlib/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@

from pandas.io.formats.printing import pprint_thing
from pandas.plotting._matplotlib.style import get_standard_colors
from pandas.plotting._matplotlib.tools import create_subplots, set_ticks_props
from pandas.plotting._matplotlib.tools import (
create_subplots,
do_adjust_figure,
maybe_adjust_figure,
set_ticks_props,
)

if TYPE_CHECKING:
from matplotlib.axes import Axes
Expand Down Expand Up @@ -39,7 +44,7 @@ def scatter_matrix(
fig, axes = create_subplots(naxes=naxes, figsize=figsize, ax=ax, squeeze=False)

# no gaps between subplots
fig.subplots_adjust(wspace=0, hspace=0)
maybe_adjust_figure(fig, wspace=0, hspace=0)

mask = notna(df)

Expand Down Expand Up @@ -329,7 +334,8 @@ def bootstrap_plot(
for axis in axes:
plt.setp(axis.get_xticklabels(), fontsize=8)
plt.setp(axis.get_yticklabels(), fontsize=8)
plt.tight_layout()
if do_adjust_figure(fig):
plt.tight_layout()
return fig


Expand Down
13 changes: 12 additions & 1 deletion pandas/plotting/_matplotlib/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,24 @@
from matplotlib.table import Table


def do_adjust_figure(fig):
if not hasattr(fig, "get_constrained_layout"):
return False
return not fig.get_constrained_layout()


def maybe_adjust_figure(fig, *args, **kwargs):
if do_adjust_figure(fig):
fig.subplots_adjust(*args, **kwargs)


def format_date_labels(ax: Axes, rot):
# mini version of autofmt_xdate
for label in ax.get_xticklabels():
label.set_ha("right")
label.set_rotation(rot)
fig = ax.get_figure()
fig.subplots_adjust(bottom=0.2)
maybe_adjust_figure(fig, bottom=0.2)


def table(
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/plotting/frame/test_frame_subplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,19 @@ def test_subplots_sharex_false(self):
tm.assert_numpy_array_equal(axs[0].get_xticks(), expected_ax1)
tm.assert_numpy_array_equal(axs[1].get_xticks(), expected_ax2)

def test_subplots_constrained_layout(self):
# GH 25261
idx = date_range(start="now", periods=10)
df = DataFrame(np.random.rand(10, 3), index=idx)
kwargs = {}
if hasattr(self.plt.Figure, "get_constrained_layout"):
kwargs["constrained_layout"] = True
fig, axes = self.plt.subplots(2, **kwargs)
with tm.assert_produces_warning(None):
df.plot(ax=axes[0])
with tm.ensure_clean(return_filelike=True) as path:
self.plt.savefig(path)

@pytest.mark.parametrize(
"index_name, old_label, new_label",
[
Expand Down