Skip to content

Commit

Permalink
Style fixes.
Browse files Browse the repository at this point in the history
... mostly found by pylint.
It did catch two tests in test_colorbar with the same name, one
shadowing the other...
  • Loading branch information
anntzer committed Aug 20, 2019
1 parent 9a43e85 commit 8b34965
Show file tree
Hide file tree
Showing 10 changed files with 144 additions and 271 deletions.
74 changes: 36 additions & 38 deletions lib/matplotlib/_constrained_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,44 +99,42 @@ def do_constrained_layout(fig, renderer, h_pad, w_pad,
"""

''' Steps:
1. get a list of unique gridspecs in this figure. Each gridspec will be
constrained separately.
2. Check for gaps in the gridspecs. i.e. if not every axes slot in the
gridspec has been filled. If empty, add a ghost axis that is made so
that it cannot be seen (though visible=True). This is needed to make
a blank spot in the layout.
3. Compare the tight_bbox of each axes to its `position`, and assume that
the difference is the space needed by the elements around the edge of
the axes (decorations) like the title, ticklabels, x-labels, etc. This
can include legends who overspill the axes boundaries.
4. Constrain gridspec elements to line up:
a) if colnum0 != colnumC, the two subplotspecs are stacked next to
each other, with the appropriate order.
b) if colnum0 == colnumC, line up the left or right side of the
_poslayoutbox (depending if it is the min or max num that is equal).
c) do the same for rows...
5. The above doesn't constrain relative sizes of the _poslayoutboxes at
all, and indeed zero-size is a solution that the solver often finds more
convenient than expanding the sizes. Right now the solution is to compare
subplotspec sizes (i.e. drowsC and drows0) and constrain the larger
_poslayoutbox to be larger than the ratio of the sizes. i.e. if drows0 >
drowsC, then ax._poslayoutbox > axc._poslayoutbox * drowsC / drows0. This
works fine *if* the decorations are similar between the axes. If the
larger subplotspec has much larger axes decorations, then the constraint
above is incorrect.
We need the greater than in the above, in general, rather than an equals
sign. Consider the case of the left column having 2 rows, and the right
column having 1 row. We want the top and bottom of the _poslayoutboxes to
line up. So that means if there are decorations on the left column axes
they will be smaller than half as large as the right hand axis.
This can break down if the decoration size for the right hand axis (the
margins) is very large. There must be a math way to check for this case.
'''
# Steps:
#
# 1. get a list of unique gridspecs in this figure. Each gridspec will be
# constrained separately.
# 2. Check for gaps in the gridspecs. i.e. if not every axes slot in the
# gridspec has been filled. If empty, add a ghost axis that is made so
# that it cannot be seen (though visible=True). This is needed to make
# a blank spot in the layout.
# 3. Compare the tight_bbox of each axes to its `position`, and assume that
# the difference is the space needed by the elements around the edge of
# the axes (decorations) like the title, ticklabels, x-labels, etc. This
# can include legends who overspill the axes boundaries.
# 4. Constrain gridspec elements to line up:
# a) if colnum0 != colnumC, the two subplotspecs are stacked next to
# each other, with the appropriate order.
# b) if colnum0 == colnumC, line up the left or right side of the
# _poslayoutbox (depending if it is the min or max num that is equal).
# c) do the same for rows...
# 5. The above doesn't constrain relative sizes of the _poslayoutboxes
# at all, and indeed zero-size is a solution that the solver often finds
# more convenient than expanding the sizes. Right now the solution is to
# compare subplotspec sizes (i.e. drowsC and drows0) and constrain the
# larger _poslayoutbox to be larger than the ratio of the sizes. i.e. if
# drows0 > drowsC, then ax._poslayoutbox > axc._poslayoutbox*drowsC/drows0.
# This works fine *if* the decorations are similar between the axes.
# If the larger subplotspec has much larger axes decorations, then the
# constraint above is incorrect.
#
# We need the greater than in the above, in general, rather than an equals
# sign. Consider the case of the left column having 2 rows, and the right
# column having 1 row. We want the top and bottom of the _poslayoutboxes
# to line up. So that means if there are decorations on the left column
# axes they will be smaller than half as large as the right hand axis.
#
# This can break down if the decoration size for the right hand axis (the
# margins) is very large. There must be a math way to check for this case.

invTransFig = fig.transFigure.inverted().transform_bbox

Expand Down
20 changes: 6 additions & 14 deletions lib/matplotlib/_layoutbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,29 +623,21 @@ def match_margins(boxes, levels=1):


def seq_id():
'''
Generate a short sequential id for layoutbox objects...
'''

global _layoutboxobjnum

return ('%06d' % (next(_layoutboxobjnum)))
"""Generate a short sequential id for layoutbox objects."""
return '%06d' % next(_layoutboxobjnum)


def print_children(lb):
'''
Print the children of the layoutbox
'''
"""Print the children of the layoutbox."""
print(lb)
for child in lb.children:
print_children(child)


def nonetree(lb):
'''
Make all elements in this tree none... This signals not to do any more
layout.
'''
"""
Make all elements in this tree none, signalling not to do any more layout.
"""
if lb is not None:
if lb.parent is None:
# Clear the solver. Hopefully this garbage collects.
Expand Down
70 changes: 29 additions & 41 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,18 +132,14 @@ def clabel(self, levels=None, *,
A list of `.Text` instances for the labels.
"""

"""
NOTES on how this all works:
clabel basically takes the input arguments and uses them to
add a list of "label specific" attributes to the ContourSet
object. These attributes are all of the form label* and names
should be fairly self explanatory.
Once these attributes are set, clabel passes control to the
labels method (case of automatic label placement) or
`BlockingContourLabeler` (case of manual label placement).
"""
# clabel basically takes the input arguments and uses them to
# add a list of "label specific" attributes to the ContourSet
# object. These attributes are all of the form label* and names
# should be fairly self explanatory.
#
# Once these attributes are set, clabel passes control to the
# labels method (case of automatic label placement) or
# `BlockingContourLabeler` (case of manual label placement).

self.labelFmt = fmt
self._use_clabeltext = use_clabeltext
Expand Down Expand Up @@ -1496,12 +1492,8 @@ def _contour_args(self, args, kwargs):

def _check_xyz(self, args, kwargs):
"""
For functions like contour, check that the dimensions
of the input arrays match; if x and y are 1D, convert
them to 2D using meshgrid.
Possible change: I think we should make and use an ArgumentError
Exception class (here and elsewhere).
Check that the shapes of the input arrays match; if x and y are 1D,
convert them to 2D using meshgrid.
"""
x, y = args[:2]
kwargs = self.ax._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
Expand All @@ -1513,39 +1505,34 @@ def _check_xyz(self, args, kwargs):
z = ma.asarray(args[2], dtype=np.float64)

if z.ndim != 2:
raise TypeError("Input z must be a 2D array.")
elif z.shape[0] < 2 or z.shape[1] < 2:
raise TypeError("Input z must be at least a 2x2 array.")
else:
Ny, Nx = z.shape
raise TypeError(f"Input z must be 2D, not {z.ndim}D")
if z.shape[0] < 2 or z.shape[1] < 2:
raise TypeError(f"Input z must be at least a (2, 2) array, but "
f"has shape {z.shape}")
Ny, Nx = z.shape

if x.ndim != y.ndim:
raise TypeError("Number of dimensions of x and y should match.")

raise TypeError(f"Dimensionalities of x ({x.ndim}) and y "
f"({y.ndim}) do not match")
if x.ndim == 1:

nx, = x.shape
ny, = y.shape

if nx != Nx:
raise TypeError("Length of x must be number of columns in z.")

raise TypeError(f"Length of x ({nx}) must match number of "
f"columns in z ({Nx})")
if ny != Ny:
raise TypeError("Length of y must be number of rows in z.")

raise TypeError(f"Length of y ({ny}) must match number of "
f"rows in z ({Ny})")
x, y = np.meshgrid(x, y)

elif x.ndim == 2:

if x.shape != z.shape:
raise TypeError("Shape of x does not match that of z: found "
"{0} instead of {1}.".format(x.shape, z.shape))

raise TypeError(
f"Shapes of x {x.shape} and z {z.shape} do not match")
if y.shape != z.shape:
raise TypeError("Shape of y does not match that of z: found "
"{0} instead of {1}.".format(y.shape, z.shape))
raise TypeError(
f"Shapes of y {y.shape} and z {z.shape} do not match")
else:
raise TypeError("Inputs x and y must be 1D or 2D.")
raise TypeError(f"Inputs x and y must be 1D or 2D, not {x.ndim}D")

return x, y, z

Expand All @@ -1563,9 +1550,10 @@ def _initialize_x_y(self, z):
will give the minimum and maximum values of x and y.
"""
if z.ndim != 2:
raise TypeError("Input must be a 2D array.")
raise TypeError(f"Input z must be 2D, not {z.ndim}D")
elif z.shape[0] < 2 or z.shape[1] < 2:
raise TypeError("Input z must be at least a 2x2 array.")
raise TypeError(f"Input z must be at least a (2, 2) array, but "
f"has shape {z.shape}")
else:
Ny, Nx = z.shape
if self.origin is None: # Not for image-matching.
Expand Down
17 changes: 5 additions & 12 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,25 +74,18 @@ def artist_picker(self, legend, evt):
return self.legend.contains(evt)

def finalize_offset(self):
loc_in_canvas = self.get_loc_in_canvas()

if self._update == "loc":
self._update_loc(loc_in_canvas)
elif self._update == "bbox":
self._update_bbox_to_anchor(loc_in_canvas)
else:
raise RuntimeError("update parameter '%s' is not supported." %
self.update)
update_method = cbook._check_getitem(
{"loc": self._update_loc, "bbox": self._bbox_to_anchor},
update=self._update)
update_method(self.get_loc_in_canvas())

def _update_loc(self, loc_in_canvas):
bbox = self.legend.get_bbox_to_anchor()

# if bbox has zero width or height, the transformation is
# ill-defined. Fall back to the defaul bbox_to_anchor.
# ill-defined. Fall back to the default bbox_to_anchor.
if bbox.width == 0 or bbox.height == 0:
self.legend.set_bbox_to_anchor(None)
bbox = self.legend.get_bbox_to_anchor()

_bbox_transform = BboxTransformFrom(bbox)
self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas))

Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/tests/test_animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import weakref

import numpy as np
from pathlib import Path
import pytest

import matplotlib as mpl
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ def test_colorbar_scale_reset():
assert cbar.ax.yaxis.get_scale() == 'linear'


def test_colorbar_get_ticks():
def test_colorbar_get_ticks_2():
with rc_context({'_internal.classic_mode': False}):

fig, ax = plt.subplots()
Expand Down

0 comments on commit 8b34965

Please sign in to comment.