Skip to content

[Bug]: Different behavior of tight_layout and set_tight_layout with matplotlib 3.5.0 on macOS #21673

Open
@alexander-held

Description

@alexander-held

Bug summary

Since matplotlib 3.5.0, I see a slightly different result when using tight_layout() or set_tight_layout(True) with the macOS backend. These differences do not appear with matplotlib 3.4.3, or in a Debian container.

Code for reproduction

import matplotlib.pyplot as plt
from matplotlib.testing.compare import compare_images


fig1, ax1 = plt.subplots()
fig1.set_tight_layout(True)
fig1.savefig("1.png")

fig2, ax2 = plt.subplots()
fig2.tight_layout()
fig2.savefig("2.png")

assert compare_images("1.png", "2.png", 0) is None

Actual outcome

The comparison fails, and the figures slightly differ on macOS:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    assert compare_images("1.png", "2.png", 0) is None
AssertionError

The difference is rather small: the rightmost x-axis tick label slightly moves.

On Debian the assertion succeeds, and when downgrading to matplotlib 3.4.3 it also succeeds on macOS.

Expected outcome

According to the tight layout guide:

Note that matplotlib.pyplot.tight_layout() will only adjust the subplot params when it is called. In order to perform this adjustment each time the figure is redrawn, you can call fig.set_tight_layout(True), or, equivalently, set rcParams["figure.autolayout"] (default: False) to True.

I expect both figures to be equivalent, as there is nothing else happening after the tight_layout() / set_tight_layout(True) call and before saving.

Additional information

I can only reproduce the behavior on macOS with matplotlib 3.5.0. Earlier versions produce consistent figures, and a Debian container with python:3.9-slim also produces consistent figures with matplotlib 3.4.3.

I came across this while trying to understand differences in figure layout observed between CI running Ubuntu and a local macOS setup, which appeared with matplotlib 3.5.0 when using tight_layout(). These differences disappear with set_tight_layout(True), and I also see consistent behavior with constrained_layout.

While the observed difference in the example above is very small, the differences become slightly larger with more complex setups. This gist shows another figure comparison where the differences are a bit more noticeable (though still small, and hard to see unless flipping back and forth between the images).

When switching the backend to TkAgg (matplotlib.use("TkAgg")), the discrepancy also disappears.

Operating system

macOS 11.5.2

Matplotlib Version

3.5.0

Matplotlib Backend

MacOSX

Python version

Python 3.8.10

Jupyter version

6.4.0

Installation

pip

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions