Skip to content

Commit cf6032e

Browse files
committed
Fix behaviour of Figure.clear() for SubplotParams
1 parent c74365f commit cf6032e

File tree

4 files changed

+90
-21
lines changed

4 files changed

+90
-21
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
subplots_adjust has a new ``kwarg``: ``rc_default``
2+
---------------------------------------------------
3+
4+
`.Figure.subplots_adjust` and `.pyplot.subplots_adjust` have a new ``kwarg``:
5+
``rc_default`` that determines the default values for the subplot parameters.
6+
7+
The `.figure.SubplotParams` object has a new get method
8+
:meth:`~.SubplotParams.get_subplot_params`
9+
10+
When calling `.Figure.clear()` the settings for `SubplotParams` are restored to the default values.

lib/matplotlib/figure.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,7 @@ def clear(self, keep_observers=False):
925925
self.texts = []
926926
self.images = []
927927
self.legends = []
928+
self.subplotpars.update(rc_default=True)
928929
if not keep_observers:
929930
self._axobservers = cbook.CallbackRegistry()
930931
self._suptitle = None
@@ -1250,7 +1251,7 @@ def colorbar(
12501251
return cb
12511252

12521253
def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
1253-
wspace=None, hspace=None):
1254+
wspace=None, hspace=None, rc_default=False):
12541255
"""
12551256
Adjust the subplot layout parameters.
12561257
@@ -1277,6 +1278,10 @@ def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
12771278
hspace : float, optional
12781279
The height of the padding between subplots,
12791280
as a fraction of the average Axes height.
1281+
rc_default : bool
1282+
Determine the defaults. *False*, the default, and the values
1283+
are unchanged. *True* and the values are taken from
1284+
:rc:`figure.subplot.*`
12801285
"""
12811286
if (self.get_layout_engine() is not None and
12821287
not self.get_layout_engine().adjust_compatible):
@@ -1285,7 +1290,7 @@ def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
12851290
"incompatible with subplots_adjust and/or tight_layout; "
12861291
"not calling subplots_adjust.")
12871292
return
1288-
self.subplotpars.update(left, bottom, right, top, wspace, hspace)
1293+
self.subplotpars.update(left, bottom, right, top, wspace, hspace, rc_default = rc_default)
12891294
for ax in self.axes:
12901295
if ax.get_subplotspec() is not None:
12911296
ax._set_position(ax.get_subplotspec().get_position(self))

lib/matplotlib/gridspec.py

+32-19
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,7 @@ def subgridspec(self, nrows, ncols, **kwargs):
728728
return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs)
729729

730730

731+
731732
class SubplotParams:
732733
"""
733734
Parameters defining the positioning of a subplots grid in a figure.
@@ -740,49 +741,61 @@ def __init__(self, left=None, bottom=None, right=None, top=None,
740741
741742
Parameters
742743
----------
743-
left : float
744+
left : float, optional
744745
The position of the left edge of the subplots,
745746
as a fraction of the figure width.
746-
right : float
747+
right : float, optional
747748
The position of the right edge of the subplots,
748749
as a fraction of the figure width.
749-
bottom : float
750+
bottom : float, optional
750751
The position of the bottom edge of the subplots,
751752
as a fraction of the figure height.
752-
top : float
753+
top : float, optional
753754
The position of the top edge of the subplots,
754755
as a fraction of the figure height.
755-
wspace : float
756+
wspace : float, optional
756757
The width of the padding between subplots,
757758
as a fraction of the average Axes width.
758-
hspace : float
759+
hspace : float, optional
759760
The height of the padding between subplots,
760761
as a fraction of the average Axes height.
761762
"""
762763
for key in ["left", "bottom", "right", "top", "wspace", "hspace"]:
763764
setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])
764765
self.update(left, bottom, right, top, wspace, hspace)
765766

767+
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
768+
del cycle
769+
s = f"{self.__class__.__name__}(left={self.left}, bottom={self.bottom}, right={self.right}, top={self.top}, " + f"wspace={self.wspace}, hspace={self.hspace})\n"
770+
p.text(s)
771+
766772
def update(self, left=None, bottom=None, right=None, top=None,
767-
wspace=None, hspace=None):
773+
wspace=None, hspace=None, rc_default=False):
768774
"""
769775
Update the dimensions of the passed parameters. *None* means unchanged.
776+
If *rc_default* is True, then restore the parameters with value *None* to the default.
770777
"""
771778
if ((left if left is not None else self.left)
772779
>= (right if right is not None else self.right)):
773780
raise ValueError('left cannot be >= right')
774781
if ((bottom if bottom is not None else self.bottom)
775782
>= (top if top is not None else self.top)):
776783
raise ValueError('bottom cannot be >= top')
777-
if left is not None:
778-
self.left = left
779-
if right is not None:
780-
self.right = right
781-
if bottom is not None:
782-
self.bottom = bottom
783-
if top is not None:
784-
self.top = top
785-
if wspace is not None:
786-
self.wspace = wspace
787-
if hspace is not None:
788-
self.hspace = hspace
784+
785+
attributes = {'left': left, 'right': right, 'bottom': bottom, 'top': top, 'hspace': hspace, 'wspace': wspace}
786+
for key, value in attributes.items():
787+
if value is None:
788+
if rc_default:
789+
setattr(self, key, mpl.rcParams[f'figure.subplot.{key}'])
790+
else:
791+
setattr(self, key, value)
792+
793+
def get_subplot_params(self) -> dict[str, float]:
794+
"""
795+
Returns
796+
-------
797+
subplot_params : dictionary
798+
A dictionary with the subplot parameters
799+
"""
800+
return self.__dict__.copy()
801+

lib/matplotlib/tests/test_figure.py

+41
Original file line numberDiff line numberDiff line change
@@ -1706,3 +1706,44 @@ def test_warn_colorbar_mismatch():
17061706
subfig3_1.colorbar(im3_2) # should not warn
17071707
with pytest.warns(UserWarning, match="different Figure"):
17081708
subfig3_1.colorbar(im4_1)
1709+
1710+
def test_clf_subplotpars():
1711+
keys = ('left', 'right', 'bottom', 'top', 'wspace', 'hspace')
1712+
rc_params = {key: plt.rcParams['figure.subplot.'+key] for key in keys}
1713+
1714+
fig = plt.figure(1)
1715+
fig.subplots_adjust(left=0.1)
1716+
fig.clf()
1717+
assert fig.subplotpars.get_subplot_params() == rc_params
1718+
1719+
1720+
def test_suplots_adjust_1():
1721+
fig = plt.figure(1)
1722+
wspace = 0
1723+
fig.subplots_adjust(wspace=wspace)
1724+
inDict = dict(left=0.1, right=0.7, bottom=0, top=0.9, hspace=0.05)
1725+
fig.subplots_adjust(**inDict)
1726+
inDict['wspace'] = wspace
1727+
assert fig.subplotpars.get_subplot_params() == inDict
1728+
1729+
1730+
def test_suplots_adjust_2():
1731+
fig = plt.figure(1)
1732+
fig.subplots_adjust(wspace=0)
1733+
inDict = dict(left=0.1, right=0.7, bottom=0, top=0.9, hspace=0.05,
1734+
rc_default=True)
1735+
fig.subplots_adjust(**inDict)
1736+
inDict['wspace'] = plt.rcParams['figure.subplot.wspace']
1737+
del inDict['rc_default']
1738+
assert fig.subplotpars.get_subplot_params() == inDict
1739+
1740+
1741+
def test_suplots_adjust_plt():
1742+
plt.figure(1)
1743+
plt.subplots_adjust(wspace=0)
1744+
inDict = dict(left=0.1, right=0.7, bottom=0, top=0.9, hspace=0.05,
1745+
rc_default=True)
1746+
plt.subplots_adjust(**inDict)
1747+
inDict['wspace'] = plt.rcParams['figure.subplot.wspace']
1748+
del inDict['rc_default']
1749+
assert plt.gcf().subplotpars.get_subplot_params() == inDict

0 commit comments

Comments
 (0)