Skip to content

Commit e9cfec7

Browse files
committed
API: rename the first argument of subplot_mosaic to be mosaic
This gives us the option to in the future combine *tight_layout* and *constrained_layout* into a single *layout* kwarg.
1 parent f6790c0 commit e9cfec7

File tree

4 files changed

+65
-55
lines changed

4 files changed

+65
-55
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Rename fist arg to subplot_mosaic
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
4+
Both `.FigureBase.subplot_mosaic`, and `.pyplot.subplot_mosaic` have had the
5+
first position argument renamed from *layout* to *mosaic*. This is because we
6+
are considering to consolidate *constrained_layout* and *tight_layout* keyword
7+
arguments in the Figure creation functions of `pyplot` into a single *layout*
8+
keyword argument which would collide.
9+
10+
As this API is provisional, we are changing this with no deprecation period.

lib/matplotlib/figure.py

+36-36
Original file line numberDiff line numberDiff line change
@@ -1648,7 +1648,7 @@ def _normalize_grid_string(layout):
16481648
layout = inspect.cleandoc(layout)
16491649
return [list(ln) for ln in layout.strip('\n').split('\n')]
16501650

1651-
def subplot_mosaic(self, layout, *, sharex=False, sharey=False,
1651+
def subplot_mosaic(self, mosaic, *, sharex=False, sharey=False,
16521652
subplot_kw=None, gridspec_kw=None, empty_sentinel='.'):
16531653
"""
16541654
Build a layout of Axes based on ASCII art or nested lists.
@@ -1662,7 +1662,7 @@ def subplot_mosaic(self, layout, *, sharex=False, sharey=False,
16621662
16631663
Parameters
16641664
----------
1665-
layout : list of list of {hashable or nested} or str
1665+
mosaic : list of list of {hashable or nested} or str
16661666
16671667
A visual layout of how you want your Axes to be arranged
16681668
labeled as strings. For example ::
@@ -1727,8 +1727,8 @@ def subplot_mosaic(self, layout, *, sharex=False, sharey=False,
17271727
subplot_kw = subplot_kw or {}
17281728
gridspec_kw = gridspec_kw or {}
17291729
# special-case string input
1730-
if isinstance(layout, str):
1731-
layout = self._normalize_grid_string(layout)
1730+
if isinstance(mosaic, str):
1731+
mosaic = self._normalize_grid_string(mosaic)
17321732
# Only accept strict bools to allow a possible future API expansion.
17331733
_api.check_isinstance(bool, sharex=sharex, sharey=sharey)
17341734

@@ -1748,10 +1748,10 @@ def _make_array(inp):
17481748
"""
17491749
r0, *rest = inp
17501750
if isinstance(r0, str):
1751-
raise ValueError('List layout specification must be 2D')
1751+
raise ValueError('List mosaic specification must be 2D')
17521752
for j, r in enumerate(rest, start=1):
17531753
if isinstance(r, str):
1754-
raise ValueError('List layout specification must be 2D')
1754+
raise ValueError('List mosaic specification must be 2D')
17551755
if len(r0) != len(r):
17561756
raise ValueError(
17571757
"All of the rows must be the same length, however "
@@ -1764,24 +1764,24 @@ def _make_array(inp):
17641764
out[j, k] = v
17651765
return out
17661766

1767-
def _identify_keys_and_nested(layout):
1767+
def _identify_keys_and_nested(mosaic):
17681768
"""
1769-
Given a 2D object array, identify unique IDs and nested layouts
1769+
Given a 2D object array, identify unique IDs and nested mosaics
17701770
17711771
Parameters
17721772
----------
1773-
layout : 2D numpy object array
1773+
mosaic : 2D numpy object array
17741774
17751775
Returns
17761776
-------
17771777
unique_ids : tuple
1778-
The unique non-sub layout entries in this layout
1778+
The unique non-sub mosaic entries in this mosaic
17791779
nested : dict[tuple[int, int]], 2D object array
17801780
"""
17811781
# make sure we preserve the user supplied order
17821782
unique_ids = cbook._OrderedSet()
17831783
nested = {}
1784-
for j, row in enumerate(layout):
1784+
for j, row in enumerate(mosaic):
17851785
for k, v in enumerate(row):
17861786
if v == empty_sentinel:
17871787
continue
@@ -1792,102 +1792,102 @@ def _identify_keys_and_nested(layout):
17921792

17931793
return tuple(unique_ids), nested
17941794

1795-
def _do_layout(gs, layout, unique_ids, nested):
1795+
def _do_layout(gs, mosaic, unique_ids, nested):
17961796
"""
1797-
Recursively do the layout.
1797+
Recursively do the mosaic.
17981798
17991799
Parameters
18001800
----------
18011801
gs : GridSpec
1802-
layout : 2D object array
1802+
mosaic : 2D object array
18031803
The input converted to a 2D numpy array for this level.
18041804
unique_ids : tuple
18051805
The identified scalar labels at this level of nesting.
18061806
nested : dict[tuple[int, int]], 2D object array
1807-
The identified nested layouts, if any.
1807+
The identified nested mosaics, if any.
18081808
18091809
Returns
18101810
-------
18111811
dict[label, Axes]
18121812
A flat dict of all of the Axes created.
18131813
"""
1814-
rows, cols = layout.shape
1814+
rows, cols = mosaic.shape
18151815
output = dict()
18161816

18171817
# we need to merge together the Axes at this level and the axes
1818-
# in the (recursively) nested sub-layouts so that we can add
1818+
# in the (recursively) nested sub-mosaics so that we can add
18191819
# them to the figure in the "natural" order if you were to
18201820
# ravel in c-order all of the Axes that will be created
18211821
#
18221822
# This will stash the upper left index of each object (axes or
1823-
# nested layout) at this level
1823+
# nested mosaic) at this level
18241824
this_level = dict()
18251825

18261826
# go through the unique keys,
18271827
for name in unique_ids:
18281828
# sort out where each axes starts/ends
1829-
indx = np.argwhere(layout == name)
1829+
indx = np.argwhere(mosaic == name)
18301830
start_row, start_col = np.min(indx, axis=0)
18311831
end_row, end_col = np.max(indx, axis=0) + 1
18321832
# and construct the slice object
18331833
slc = (slice(start_row, end_row), slice(start_col, end_col))
18341834
# some light error checking
1835-
if (layout[slc] != name).any():
1835+
if (mosaic[slc] != name).any():
18361836
raise ValueError(
1837-
f"While trying to layout\n{layout!r}\n"
1837+
f"While trying to layout\n{mosaic!r}\n"
18381838
f"we found that the label {name!r} specifies a "
18391839
"non-rectangular or non-contiguous area.")
18401840
# and stash this slice for later
18411841
this_level[(start_row, start_col)] = (name, slc, 'axes')
18421842

1843-
# do the same thing for the nested layouts (simpler because these
1843+
# do the same thing for the nested mosaics (simpler because these
18441844
# can not be spans yet!)
1845-
for (j, k), nested_layout in nested.items():
1846-
this_level[(j, k)] = (None, nested_layout, 'nested')
1845+
for (j, k), nested_mosaic in nested.items():
1846+
this_level[(j, k)] = (None, nested_mosaic, 'nested')
18471847

18481848
# now go through the things in this level and add them
18491849
# in order left-to-right top-to-bottom
18501850
for key in sorted(this_level):
18511851
name, arg, method = this_level[key]
18521852
# we are doing some hokey function dispatch here based
18531853
# on the 'method' string stashed above to sort out if this
1854-
# element is an axes or a nested layout.
1854+
# element is an axes or a nested mosaic.
18551855
if method == 'axes':
18561856
slc = arg
18571857
# add a single axes
18581858
if name in output:
18591859
raise ValueError(f"There are duplicate keys {name} "
1860-
f"in the layout\n{layout!r}")
1860+
f"in the layout\n{mosaic!r}")
18611861
ax = self.add_subplot(
18621862
gs[slc], **{'label': str(name), **subplot_kw}
18631863
)
18641864
output[name] = ax
18651865
elif method == 'nested':
1866-
nested_layout = arg
1866+
nested_mosaic = arg
18671867
j, k = key
1868-
# recursively add the nested layout
1869-
rows, cols = nested_layout.shape
1868+
# recursively add the nested mosaic
1869+
rows, cols = nested_mosaic.shape
18701870
nested_output = _do_layout(
18711871
gs[j, k].subgridspec(rows, cols, **gridspec_kw),
1872-
nested_layout,
1873-
*_identify_keys_and_nested(nested_layout)
1872+
nested_mosaic,
1873+
*_identify_keys_and_nested(nested_mosaic)
18741874
)
18751875
overlap = set(output) & set(nested_output)
18761876
if overlap:
18771877
raise ValueError(
18781878
f"There are duplicate keys {overlap} "
1879-
f"between the outer layout\n{layout!r}\n"
1880-
f"and the nested layout\n{nested_layout}"
1879+
f"between the outer layout\n{mosaic!r}\n"
1880+
f"and the nested layout\n{nested_mosaic}"
18811881
)
18821882
output.update(nested_output)
18831883
else:
18841884
raise RuntimeError("This should never happen")
18851885
return output
18861886

1887-
layout = _make_array(layout)
1888-
rows, cols = layout.shape
1887+
mosaic = _make_array(mosaic)
1888+
rows, cols = mosaic.shape
18891889
gs = self.add_gridspec(rows, cols, **gridspec_kw)
1890-
ret = _do_layout(gs, layout, *_identify_keys_and_nested(layout))
1890+
ret = _do_layout(gs, mosaic, *_identify_keys_and_nested(mosaic))
18911891
ax0 = next(iter(ret.values()))
18921892
for ax in ret.values():
18931893
if sharex:

lib/matplotlib/pyplot.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1432,7 +1432,7 @@ def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
14321432
return fig, axs
14331433

14341434

1435-
def subplot_mosaic(layout, *, sharex=False, sharey=False,
1435+
def subplot_mosaic(mosaic, *, sharex=False, sharey=False,
14361436
subplot_kw=None, gridspec_kw=None, empty_sentinel='.',
14371437
**fig_kw):
14381438
"""
@@ -1447,7 +1447,7 @@ def subplot_mosaic(layout, *, sharex=False, sharey=False,
14471447
14481448
Parameters
14491449
----------
1450-
layout : list of list of {hashable or nested} or str
1450+
mosaic : list of list of {hashable or nested} or str
14511451
14521452
A visual layout of how you want your Axes to be arranged
14531453
labeled as strings. For example ::
@@ -1513,7 +1513,7 @@ def subplot_mosaic(layout, *, sharex=False, sharey=False,
15131513
"""
15141514
fig = figure(**fig_kw)
15151515
ax_dict = fig.subplot_mosaic(
1516-
layout, sharex=sharex, sharey=sharey,
1516+
mosaic, sharex=sharex, sharey=sharey,
15171517
subplot_kw=subplot_kw, gridspec_kw=gridspec_kw,
15181518
empty_sentinel=empty_sentinel
15191519
)

tutorials/provisional/mosaic.py

+16-16
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def identify_axes(ax_dict, fontsize=48):
7676
)
7777

7878
###############################################################################
79-
# Using `.Figure.subplot_mosaic` we can produce the same layout but give the
79+
# Using `.Figure.subplot_mosaic` we can produce the same mosaic but give the
8080
# axes semantic names
8181

8282
fig = plt.figure(constrained_layout=True)
@@ -106,18 +106,18 @@ def identify_axes(ax_dict, fontsize=48):
106106
# "draw" the Axes we want as "ASCII art". The following
107107

108108

109-
layout = """
109+
mosaic = """
110110
AB
111111
CD
112112
"""
113113

114114
###############################################################################
115115
# will give us 4 Axes laid out in a 2x2 grid and generates the same
116-
# figure layout as above (but now labeled with ``{"A", "B", "C",
116+
# figure mosaic as above (but now labeled with ``{"A", "B", "C",
117117
# "D"}`` rather than ``{"bar", "plot", "hist", "image"}``).
118118

119119
fig = plt.figure(constrained_layout=True)
120-
ax_dict = fig.subplot_mosaic(layout)
120+
ax_dict = fig.subplot_mosaic(mosaic)
121121
identify_axes(ax_dict)
122122

123123

@@ -183,7 +183,7 @@ def identify_axes(ax_dict, fontsize=48):
183183
# empty sentinel with the string shorthand because it may be stripped
184184
# while processing the input.
185185
#
186-
# Controlling layout and subplot creation
186+
# Controlling mosaic and subplot creation
187187
# =======================================
188188
#
189189
# This feature is built on top of `.gridspec` and you can pass the
@@ -211,14 +211,14 @@ def identify_axes(ax_dict, fontsize=48):
211211

212212
###############################################################################
213213
# Or use the {*left*, *right*, *bottom*, *top*} keyword arguments to
214-
# position the overall layout to put multiple versions of the same
215-
# layout in a figure
214+
# position the overall mosaic to put multiple versions of the same
215+
# mosaic in a figure
216216

217-
layout = """AA
217+
mosaic = """AA
218218
BC"""
219219
fig = plt.figure()
220220
axd = fig.subplot_mosaic(
221-
layout,
221+
mosaic,
222222
gridspec_kw={
223223
"bottom": 0.25,
224224
"top": 0.95,
@@ -231,7 +231,7 @@ def identify_axes(ax_dict, fontsize=48):
231231
identify_axes(axd)
232232

233233
axd = fig.subplot_mosaic(
234-
layout,
234+
mosaic,
235235
gridspec_kw={
236236
"bottom": 0.05,
237237
"top": 0.75,
@@ -274,30 +274,30 @@ def identify_axes(ax_dict, fontsize=48):
274274

275275

276276
###############################################################################
277-
# In addition, using the list input we can specify nested layouts. Any element
277+
# In addition, using the list input we can specify nested mosaics. Any element
278278
# of the inner list can be another set of nested lists:
279279

280280
inner = [
281281
["inner A"],
282282
["inner B"],
283283
]
284284

285-
outer_nested_layout = [
285+
outer_nested_mosaic = [
286286
["main", inner],
287287
["bottom", "bottom"],
288288
]
289289
axd = plt.figure(constrained_layout=True).subplot_mosaic(
290-
outer_nested_layout, empty_sentinel=None
290+
outer_nested_mosaic, empty_sentinel=None
291291
)
292292
identify_axes(axd, fontsize=36)
293293

294294

295295
###############################################################################
296296
# We can also pass in a 2D NumPy array to do things like
297-
layout = np.zeros((4, 4), dtype=int)
297+
mosaic = np.zeros((4, 4), dtype=int)
298298
for j in range(4):
299-
layout[j, j] = j + 1
299+
mosaic[j, j] = j + 1
300300
axd = plt.figure(constrained_layout=True).subplot_mosaic(
301-
layout, empty_sentinel=0
301+
mosaic, empty_sentinel=0
302302
)
303303
identify_axes(axd)

0 commit comments

Comments
 (0)