Skip to content

Getters setters #25901

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
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
65 changes: 65 additions & 0 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1201,6 +1201,67 @@
self.stale = True
return text

def set_subplotparams(self, subplotparams={}):
"""
Set the subplot layout parameters.

Accepts either a `.SubplotParams` object, from which the relevant
parameters are copied, or a dictionary of subplot layout parameters.
If a dictionary is provided, this function is a convenience wrapper for
`matplotlib.figure.Figure.subplots_adjust`

Parameters
----------
subplotparams : `~matplotlib.figure.SubplotParams` or dict with keys
"left", "bottom", "right", 'top", "wspace", "hspace"] , optional
SubplotParams object to copy new subplot parameters from, or a dict
of SubplotParams constructor arguments.
By default, an empty dictionary is passed, which maintains the
current state of the figure's `.SubplotParams`

See Also
--------

Check warning on line 1223 in lib/matplotlib/figure.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/figure.py#L1223

Added line #L1223 was not covered by tests
matplotlib.figure.Figure.subplots_adjust
matplotlib.figure.Figure.get_subplotparams
"""

subplotparams_args = ["left", "bottom", "right",
"top", "wspace", "hspace"]
kwargs = {}
if isinstance(subplotparams, SubplotParams):
for key in subplotparams_args:
kwargs[key] = getattr(subplotparams, key)
elif isinstance(subplotparams, dict):
for key in subplotparams.keys():
if key in subplotparams_args:
kwargs[key] = subplotparams[key]

Check warning on line 1237 in lib/matplotlib/figure.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/figure.py#L1237

Added line #L1237 was not covered by tests
else:
_api.warn_external(
f"'{key}' is not a valid key for set_subplotparams;"
" this key was ignored.")
else:
raise TypeError(
"subplotparams must be a dictionary of keyword-argument pairs or"
" an instance of SubplotParams()")
if kwargs == {}:
self.set_subplotparams(self.get_subplotparams())
self.subplots_adjust(**kwargs)

def get_subplotparams(self):
"""
Return the `.SubplotParams` object associated with the Figure.

Returns
-------
`.SubplotParams`

See Also
--------
matplotlib.figure.Figure.subplots_adjust
matplotlib.figure.Figure.get_subplotparams
"""
return self.subplotpars
Copy link
Member

Choose a reason for hiding this comment

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

The test is failing because of this line, I don't think you've defined what subplotpars is.


@_docstring.dedent_interpd
def colorbar(
self, mappable, cax=None, ax=None, use_gridspec=True, **kwargs):
Expand Down Expand Up @@ -2346,6 +2407,10 @@


@_docstring.interpd
@_api.define_aliases({
"size_inches": ["figsize"],
"layout_engine": ["layout"],
})
class Figure(FigureBase):
"""
The top level container for all the plot elements.
Expand Down
7 changes: 7 additions & 0 deletions lib/matplotlib/figure.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,13 @@ class FigureBase(Artist):
gridspec_kw: dict[str, Any] | None = ...
) -> dict[Any, Axes]: ...

def set_subplotparams(
self,
subplotparams: SubplotParams | dict[str, Any] = ...,
) -> None: ...

def get_subplotparams(self) -> SubplotParams: ...

class SubFigure(FigureBase):
figure: Figure
subplotpars: SubplotParams
Expand Down
39 changes: 39 additions & 0 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1611,3 +1611,42 @@ def test_get_constrained_layout_pads():
fig = plt.figure(layout=mpl.layout_engine.ConstrainedLayoutEngine(**params))
with pytest.warns(PendingDeprecationWarning, match="will be deprecated"):
assert fig.get_constrained_layout_pads() == expected


def test_get_subplot_params():
fig = plt.figure()
subplotparams_keys = ["left", "bottom", "right", "top", "wspace", "hspace"]
subplotparams = fig.get_subplotparams()
test_dict = {}
for key in subplotparams_keys:
attr = getattr(subplotparams, key)
assert attr == mpl.rcParams[f"figure.subplot.{key}"]
test_dict[key] = attr * 2

fig.set_subplotparams(test_dict)
for key, value in test_dict.items():
assert getattr(fig.get_subplotparams(), key) == value

test_dict['foo'] = 'bar'
with pytest.warns(UserWarning,
match="'foo' is not a valid key for set_subplotparams;"
" this key was ignored"):
fig.set_subplotparams(test_dict)

with pytest.raises(TypeError,
match="subplotparams must be a dictionary of "
"keyword-argument pairs or "
"an instance of SubplotParams()"):
fig.set_subplotparams(['foo'])

assert fig.subplotpars == fig.get_subplotparams()


def test_fig_get_set():
varnames = filter(lambda var: var not in ['self', 'kwargs', 'args'],
Figure.__init__.__code__.co_varnames)
fig = plt.figure()
for var in varnames:
# if getattr fails then the getter and setter does not exist
getfunc = getattr(fig, f"get_{var}")
setfunc = getattr(fig, f"set_{var}")