Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 50595b5

Browse filesBrowse files
committed
Dedupe SubplotSpec construction in mpl_toolkits.
i.e. parsing subplot(i, j, k) and subplot(ijk); this is done by reusing the implementation in subplot(). Also delete some commented-out code which is clearly handled by gridspec now.
1 parent 289130d commit 50595b5
Copy full SHA for 50595b5

File tree

Expand file treeCollapse file tree

3 files changed

+49
-122
lines changed
Filter options
Expand file treeCollapse file tree

3 files changed

+49
-122
lines changed

‎lib/matplotlib/axes/_subplots.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_subplots.py
+1-38Lines changed: 1 addition & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -33,45 +33,8 @@ def __init__(self, fig, *args, **kwargs):
3333
"""
3434

3535
self.figure = fig
36-
37-
if len(args) == 1:
38-
if isinstance(args[0], SubplotSpec):
39-
self._subplotspec = args[0]
40-
else:
41-
try:
42-
s = str(int(args[0]))
43-
rows, cols, num = map(int, s)
44-
except ValueError:
45-
raise ValueError('Single argument to subplot must be '
46-
'a 3-digit integer')
47-
self._subplotspec = GridSpec(rows, cols,
48-
figure=self.figure)[num - 1]
49-
# num - 1 for converting from MATLAB to python indexing
50-
elif len(args) == 3:
51-
rows, cols, num = args
52-
rows = int(rows)
53-
cols = int(cols)
54-
if rows <= 0:
55-
raise ValueError(f'Number of rows must be > 0, not {rows}')
56-
if cols <= 0:
57-
raise ValueError(f'Number of columns must be > 0, not {cols}')
58-
if isinstance(num, tuple) and len(num) == 2:
59-
num = [int(n) for n in num]
60-
self._subplotspec = GridSpec(
61-
rows, cols,
62-
figure=self.figure)[(num[0] - 1):num[1]]
63-
else:
64-
if num < 1 or num > rows*cols:
65-
raise ValueError(
66-
f"num must be 1 <= num <= {rows*cols}, not {num}")
67-
self._subplotspec = GridSpec(
68-
rows, cols, figure=self.figure)[int(num) - 1]
69-
# num - 1 for converting from MATLAB to python indexing
70-
else:
71-
raise ValueError(f'Illegal argument(s) to subplot: {args}')
72-
36+
self._subplotspec = SubplotSpec._from_subplot_args(fig, args)
7337
self.update_params()
74-
7538
# _axes_class is set in the subplot_class_factory
7639
self._axes_class.__init__(self, fig, self.figbox, **kwargs)
7740
# add a layout box to this, for both the full axis, and the poss

‎lib/matplotlib/gridspec.py

Copy file name to clipboardExpand all lines: lib/matplotlib/gridspec.py
+41Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,47 @@ def __init__(self, gridspec, num1, num2=None):
522522
else:
523523
self._layoutbox = None
524524

525+
@staticmethod
526+
def _from_subplot_args(figure, args):
527+
"""
528+
Construct a `.SubplotSpec` from a parent `.Figure` and either
529+
530+
- a `.SubplotSpec` -- returned as is;
531+
- one or three numbers -- a MATLAB-style subplot specifier.
532+
"""
533+
if len(args) == 1:
534+
arg, = args
535+
if isinstance(arg, SubplotSpec):
536+
return arg
537+
else:
538+
try:
539+
s = str(int(arg))
540+
rows, cols, num = map(int, s)
541+
except ValueError:
542+
raise ValueError("Single argument to subplot must be a "
543+
"3-digit integer")
544+
# num - 1 for converting from MATLAB to python indexing
545+
return GridSpec(rows, cols, figure=figure)[num - 1]
546+
elif len(args) == 3:
547+
rows, cols, num = args
548+
rows = int(rows)
549+
cols = int(cols)
550+
if rows <= 0:
551+
raise ValueError(f"Number of rows must be > 0, not {rows}")
552+
if cols <= 0:
553+
raise ValueError(f"Number of columns must be > 0, not {cols}")
554+
if isinstance(num, tuple) and len(num) == 2:
555+
i, j = map(int, num)
556+
return GridSpec(rows, cols, figure=figure)[i-1:j]
557+
else:
558+
if num < 1 or num > rows*cols:
559+
raise ValueError(
560+
f"num must be 1 <= num <= {rows*cols}, not {num}")
561+
# num - 1 for converting from MATLAB to python indexing
562+
return GridSpec(rows, cols, figure=figure)[int(num) - 1]
563+
else:
564+
raise ValueError(f"Illegal argument(s) to subplot: {args}")
565+
525566
# num2 is a property only to handle the case where it is None and someone
526567
# mutates num1.
527568

‎lib/mpl_toolkits/axes_grid1/axes_divider.py

Copy file name to clipboardExpand all lines: lib/mpl_toolkits/axes_grid1/axes_divider.py
+7-84Lines changed: 7 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
object that can be used to set the axes_locator of the axes.
1111
"""
1212

13+
import numpy as np
14+
1315
from matplotlib import cbook
1416
from matplotlib.axes import SubplotBase
1517
from matplotlib.gridspec import SubplotSpec, GridSpec
@@ -274,10 +276,7 @@ def append_size(self, position, size):
274276
cbook._check_in_list(["left", "right", "bottom", "top"],
275277
position=position)
276278

277-
def add_auto_adjustable_area(self,
278-
use_axes, pad=0.1,
279-
adjust_dirs=None,
280-
):
279+
def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None):
281280
if adjust_dirs is None:
282281
adjust_dirs = ["left", "right", "bottom", "top"]
283282
from .axes_size import Padded, SizeFromFunc, GetExtentHelper
@@ -362,90 +361,18 @@ def __init__(self, fig, *args, horizontal=None, vertical=None,
362361
*args* can be passed as a single 3-digit number (e.g. 234 for
363362
(2, 3, 4)).
364363
"""
365-
366364
self.figure = fig
367-
368-
if len(args) == 1:
369-
if isinstance(args[0], SubplotSpec):
370-
self._subplotspec = args[0]
371-
else:
372-
try:
373-
s = str(int(args[0]))
374-
rows, cols, num = map(int, s)
375-
except ValueError:
376-
raise ValueError(
377-
'Single argument to subplot must be a 3-digit integer')
378-
self._subplotspec = GridSpec(rows, cols)[num-1]
379-
# num - 1 for converting from MATLAB to python indexing
380-
elif len(args) == 3:
381-
rows, cols, num = args
382-
rows = int(rows)
383-
cols = int(cols)
384-
if isinstance(num, tuple) and len(num) == 2:
385-
num = [int(n) for n in num]
386-
self._subplotspec = GridSpec(rows, cols)[num[0]-1:num[1]]
387-
else:
388-
self._subplotspec = GridSpec(rows, cols)[int(num)-1]
389-
# num - 1 for converting from MATLAB to python indexing
390-
else:
391-
raise ValueError(f'Illegal argument(s) to subplot: {args}')
392-
393-
# total = rows*cols
394-
# num -= 1 # convert from matlab to python indexing
395-
# # i.e., num in range(0, total)
396-
# if num >= total:
397-
# raise ValueError( 'Subplot number exceeds total subplots')
398-
# self._rows = rows
399-
# self._cols = cols
400-
# self._num = num
401-
402-
# self.update_params()
403-
404-
# sets self.fixbox
405-
self.update_params()
406-
407-
pos = self.figbox.bounds
408-
409-
Divider.__init__(self, fig, pos, horizontal or [], vertical or [],
365+
self._subplotspec = SubplotSpec._from_subplot_args(fig, args)
366+
self.update_params() # sets self.figbox
367+
Divider.__init__(self, fig, pos=self.figbox.bounds,
368+
horizontal=horizontal or [], vertical=vertical or [],
410369
aspect=aspect, anchor=anchor)
411370

412371
def get_position(self):
413372
"return the bounds of the subplot box"
414-
415373
self.update_params() # update self.figbox
416374
return self.figbox.bounds
417375

418-
# def update_params(self):
419-
# 'update the subplot position from fig.subplotpars'
420-
421-
# rows = self._rows
422-
# cols = self._cols
423-
# num = self._num
424-
425-
# pars = self.figure.subplotpars
426-
# left = pars.left
427-
# right = pars.right
428-
# bottom = pars.bottom
429-
# top = pars.top
430-
# wspace = pars.wspace
431-
# hspace = pars.hspace
432-
# totWidth = right-left
433-
# totHeight = top-bottom
434-
435-
# figH = totHeight/(rows + hspace*(rows-1))
436-
# sepH = hspace*figH
437-
438-
# figW = totWidth/(cols + wspace*(cols-1))
439-
# sepW = wspace*figW
440-
441-
# rowNum, colNum = divmod(num, cols)
442-
443-
# figBottom = top - (rowNum+1)*figH - rowNum*sepH
444-
# figLeft = left + colNum*(figW + sepW)
445-
446-
# self.figbox = mtransforms.Bbox.from_bounds(figLeft, figBottom,
447-
# figW, figH)
448-
449376
def update_params(self):
450377
"""Update the subplot position from fig.subplotpars."""
451378
self.figbox = self.get_subplotspec().get_position(self.figure)
@@ -664,16 +591,12 @@ def get_subplotspec(self):
664591

665592
class HBoxDivider(SubplotDivider):
666593

667-
def __init__(self, fig, *args, **kwargs):
668-
SubplotDivider.__init__(self, fig, *args, **kwargs)
669-
670594
@staticmethod
671595
def _determine_karray(equivalent_sizes, appended_sizes,
672596
max_equivalent_size,
673597
total_appended_size):
674598

675599
n = len(equivalent_sizes)
676-
import numpy as np
677600
A = np.mat(np.zeros((n+1, n+1), dtype="d"))
678601
B = np.zeros((n+1), dtype="d")
679602
# AxK = B

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.