Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 602dfbe

Browse files
committed
ENH: reuse gridspec if possible
1 parent 13c2fbd commit 602dfbe

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

lib/matplotlib/gridspec.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,8 @@ def _from_subplot_args(figure, args):
536536
raise ValueError("Single argument to subplot must be a "
537537
"3-digit integer") from err
538538
# num - 1 for converting from MATLAB to python indexing
539-
return GridSpec(rows, cols, figure=figure)[num - 1]
539+
ii = num
540+
jj = num
540541
elif len(args) == 3:
541542
rows, cols, num = args
542543
rows = int(rows)
@@ -546,17 +547,33 @@ def _from_subplot_args(figure, args):
546547
if cols <= 0:
547548
raise ValueError(f"Number of columns must be > 0, not {cols}")
548549
if isinstance(num, tuple) and len(num) == 2:
549-
i, j = map(int, num)
550-
return GridSpec(rows, cols, figure=figure)[i-1:j]
550+
ii, jj = map(int, num)
551551
else:
552552
if num < 1 or num > rows*cols:
553553
raise ValueError(
554554
f"num must be 1 <= num <= {rows*cols}, not {num}")
555555
# num - 1 for converting from MATLAB to python indexing
556-
return GridSpec(rows, cols, figure=figure)[int(num) - 1]
556+
ii = num
557+
jj = num
557558
else:
558559
raise TypeError(f"subplot() takes 1 or 3 positional arguments but "
559560
f"{len(args)} were given")
561+
for ax in figure.get_axes():
562+
if hasattr(ax, 'get_subplotspec'):
563+
gs = ax.get_subplotspec().get_gridspec()
564+
if hasattr(gs, 'get_topmost_subplotspec'):
565+
# This is needed for colorbar gridspec layouts.
566+
# This is probably OK becase this whole logic tree
567+
# is for when the user is doing simple things with the
568+
# add_subplot command. Complicated stuff, the proper
569+
# gridspec is passed in...
570+
gs = gs.get_topmost_subplotspec().get_gridspec()
571+
572+
(nrow, ncol) = gs.get_geometry()
573+
if nrow == rows and ncol == cols:
574+
return gs[ii-1:jj]
575+
return GridSpec(rows, cols, figure=figure)[ii-1:jj]
576+
560577

561578
# num2 is a property only to handle the case where it is None and someone
562579
# mutates num1.

0 commit comments

Comments
 (0)