Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
38 changes: 31 additions & 7 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -3154,7 +3154,16 @@ def set_size_inches(self, w, h=None, forward=True):
To transform from pixels to inches divide by `Figure.dpi`.
"""
if h is None: # Got called with a single pair as argument.
w, h = w
try:
w, h = w
except (TypeError, ValueError):
raise ValueError(
"Figure.set_size_inches does not accept None; provide "
"both width and height explicitly") from None
if w is None or h is None:
raise ValueError(
"Figure.set_size_inches does not accept None; provide both "
"width and height explicitly")
size = np.array([w, h])
if not np.isfinite(size).all() or (size < 0).any():
raise ValueError(f'figure size must be positive finite not {size}')
Expand Down Expand Up @@ -3763,25 +3772,40 @@ def _parse_figsize(figsize, dpi):
"""
num_parts = len(figsize)
if num_parts == 2:
return figsize
x, y = figsize
elif num_parts == 3:
x, y, unit = figsize
if unit == 'in':
pass
elif unit == 'cm':
x /= 2.54
y /= 2.54
if x is not None:
x /= 2.54
if y is not None:
y /= 2.54
elif unit == 'px':
x /= dpi
y /= dpi
if x is not None:
x /= dpi
if y is not None:
y /= dpi
else:
raise ValueError(
f"Invalid unit {unit!r} in 'figsize'; "
"supported units are 'in', 'cm', 'px'"
)
return x, y
else:
raise ValueError(
"Invalid figsize format, expected (x, y) or (x, y, unit) but got "
f"{figsize!r}"
)

if x is None and y is None:
raise ValueError(
"figsize=(None, None) is invalid; at least one of width or "
"height must be provided")

default_width, default_height = mpl.rcParams["figure.figsize"]
if x is None:
x = default_width
if y is None:
y = default_height
return x, y
18 changes: 18 additions & 0 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1883,6 +1883,24 @@ def test_figsize(figsize, figsize_inches):
assert tuple(fig.get_size_inches()) == figsize_inches


def test_figsize_partial_none():
default_w, default_h = mpl.rcParams["figure.figsize"]

fig = plt.figure(figsize=(None, 4))
w, h = fig.get_size_inches()
assert (w, h) == (default_w, 4)

fig = plt.figure(figsize=(6, None))
w, h = fig.get_size_inches()
assert (w, h) == (6, default_h)


def test_figsize_both_none():
with pytest.raises(ValueError,
match=r"figsize=\(None, None\) is invalid"):
plt.figure(figsize=(None, None))


def test_figsize_invalid_unit():
with pytest.raises(ValueError, match="Invalid unit 'um'"):
plt.figure(figsize=(6, 4, "um"))
Loading