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

Skip to content

Commit 470a1ab

Browse files
authored
Merge pull request #13854 from anntzer/contour
Cleanup contour.py.
2 parents 559925e + 2137565 commit 470a1ab

File tree

2 files changed

+32
-64
lines changed

2 files changed

+32
-64
lines changed

lib/matplotlib/contour.py

Lines changed: 27 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -38,38 +38,28 @@ class ClabelText(text.Text):
3838
angle in the pixel coordinate assuming that the input rotation is
3939
an angle in data coordinate (or whatever transform set).
4040
"""
41+
4142
def get_rotation(self):
42-
angle = text.Text.get_rotation(self)
43-
trans = self.get_transform()
44-
x, y = self.get_position()
45-
new_angles = trans.transform_angles(np.array([angle]),
46-
np.array([[x, y]]))
47-
return new_angles[0]
43+
new_angle, = self.get_transform().transform_angles(
44+
[text.Text.get_rotation(self)], [self.get_position()])
45+
return new_angle
4846

4947

5048
class ContourLabeler(object):
5149
"""Mixin to provide labelling capability to `.ContourSet`."""
5250

53-
def clabel(self, *args,
51+
def clabel(self, levels=None, *,
5452
fontsize=None, inline=True, inline_spacing=5, fmt='%1.3f',
5553
colors=None, use_clabeltext=False, manual=False,
5654
rightside_up=True):
5755
"""
5856
Label a contour plot.
5957
60-
Call signature::
61-
62-
clabel(cs, [levels,] **kwargs)
63-
64-
Adds labels to line contours in *cs*, where *cs* is a
65-
:class:`~matplotlib.contour.ContourSet` object returned by
66-
``contour()``.
58+
Adds labels to line contours in this `.ContourSet` (which inherits from
59+
this mixin class).
6760
6861
Parameters
6962
----------
70-
cs : `.ContourSet`
71-
The ContourSet to label.
72-
7363
levels : array-like, optional
7464
A list of level values, that should be labeled. The list must be
7565
a subset of ``cs.levels``. If not given, all levels are labeled.
@@ -105,11 +95,11 @@ def clabel(self, *args,
10595
fmt : string or dict, optional
10696
A format string for the label. Default is '%1.3f'
10797
108-
Alternatively, this can be a dictionary matching contour
109-
levels with arbitrary strings to use for each contour level
110-
(i.e., fmt[level]=string), or it can be any callable, such
111-
as a :class:`~matplotlib.ticker.Formatter` instance, that
112-
returns a string when called with a numeric contour level.
98+
Alternatively, this can be a dictionary matching contour levels
99+
with arbitrary strings to use for each contour level (i.e.,
100+
fmt[level]=string), or it can be any callable, such as a
101+
`.Formatter` instance, that returns a string when called with a
102+
numeric contour level.
113103
114104
manual : bool or iterable, optional
115105
If ``True``, contour labels will be placed manually using
@@ -161,21 +151,19 @@ def clabel(self, *args,
161151
self.labelManual = manual
162152
self.rightside_up = rightside_up
163153

164-
if len(args) == 0:
154+
if levels is None:
165155
levels = self.levels
166156
indices = list(range(len(self.cvalues)))
167-
elif len(args) == 1:
168-
levlabs = list(args[0])
157+
else:
158+
levlabs = list(levels)
169159
indices, levels = [], []
170160
for i, lev in enumerate(self.levels):
171161
if lev in levlabs:
172162
indices.append(i)
173163
levels.append(lev)
174164
if len(levels) < len(levlabs):
175-
raise ValueError("Specified levels {} don't match available "
176-
"levels {}".format(levlabs, self.levels))
177-
else:
178-
raise TypeError("Illegal arguments to clabel, see help(clabel)")
165+
raise ValueError(f"Specified levels {levlabs} don't match "
166+
f"available levels {self.levels}")
179167
self.labelLevelList = levels
180168
self.labelIndiceList = indices
181169

@@ -197,15 +185,12 @@ def clabel(self, *args,
197185

198186
if np.iterable(self.labelManual):
199187
for x, y in self.labelManual:
200-
self.add_label_near(x, y, inline,
201-
inline_spacing)
202-
188+
self.add_label_near(x, y, inline, inline_spacing)
203189
elif self.labelManual:
204190
print('Select label locations manually using first mouse button.')
205191
print('End manual selection with second mouse button.')
206192
if not inline:
207193
print('Remove last label by clicking third mouse button.')
208-
209194
blocking_contour_labeler = BlockingContourLabeler(self)
210195
blocking_contour_labeler(inline, inline_spacing)
211196
else:
@@ -262,13 +247,10 @@ def get_label_width(self, lev, fmt, fsize):
262247
"""
263248
if not isinstance(lev, str):
264249
lev = self.get_text(lev, fmt)
265-
266250
lev, ismath = text.Text()._preprocess_math(lev)
267251
if ismath == 'TeX':
268-
if not hasattr(self, '_TeX_manager'):
269-
self._TeX_manager = texmanager.TexManager()
270-
lw, _, _ = self._TeX_manager.get_text_width_height_descent(lev,
271-
fsize)
252+
lw, _, _ = (texmanager.TexManager()
253+
.get_text_width_height_descent(lev, fsize))
272254
elif ismath:
273255
if not hasattr(self, '_mathtext_parser'):
274256
self._mathtext_parser = mathtext.MathTextParser('bitmap')
@@ -277,8 +259,7 @@ def get_label_width(self, lev, fmt, fsize):
277259
lw = img.get_width() # at dpi=72, the units are PostScript points
278260
else:
279261
# width is much less than "font size"
280-
lw = (len(lev)) * fsize * 0.6
281-
262+
lw = len(lev) * fsize * 0.6
282263
return lw
283264

284265
def set_label_props(self, label, text, color):
@@ -465,7 +446,6 @@ def add_label(self, x, y, rotation, lev, cvalue):
465446
"""
466447
Add contour label using :class:`~matplotlib.text.Text` class.
467448
"""
468-
469449
t = self._get_label_text(x, y, rotation)
470450
self._add_label(t, x, y, lev, cvalue)
471451

@@ -477,7 +457,6 @@ def add_label_clabeltext(self, x, y, rotation, lev, cvalue):
477457
# the data coordinate and create a label using ClabelText
478458
# class. This way, the rotation of the clabel is along the
479459
# contour line always.
480-
481460
t = self._get_label_clabeltext(x, y, rotation)
482461
self._add_label(t, x, y, lev, cvalue)
483462

@@ -633,8 +612,7 @@ def labels(self, inline, inline_spacing):
633612
# After looping over all segments on a contour, remove old
634613
# paths and add new ones if inlining
635614
if inline:
636-
del paths[:]
637-
paths.extend(additions)
615+
paths[:] = additions
638616

639617

640618
def _find_closest_point_on_leg(p1, p2, p0):
@@ -1032,15 +1010,11 @@ def legend_elements(self, variable_name='x', str_format=str):
10321010
upper = str_format(upper)
10331011

10341012
if i == 0 and self.extend in ('min', 'both'):
1035-
labels.append(r'$%s \leq %s$' % (variable_name,
1036-
lower))
1013+
labels.append(fr'${variable_name} \leq {lower}s$')
10371014
elif i == n_levels - 1 and self.extend in ('max', 'both'):
1038-
labels.append(r'$%s > %s$' % (variable_name,
1039-
upper))
1015+
labels.append(fr'${variable_name} > {upper}s$')
10401016
else:
1041-
labels.append(r'$%s < %s \leq %s$' % (lower,
1042-
variable_name,
1043-
upper))
1017+
labels.append(fr'${lower} < {variable_name} \leq {upper}$')
10441018
else:
10451019
for collection, level in zip(self.collections, self.levels):
10461020

@@ -1050,7 +1024,7 @@ def legend_elements(self, variable_name='x', str_format=str):
10501024
artists.append(patch)
10511025
# format the level for insertion into the labels
10521026
level = str_format(level)
1053-
labels.append(r'$%s = %s$' % (variable_name, level))
1027+
labels.append(fr'${variable_name} = {level}$')
10541028

10551029
return artists, labels
10561030

@@ -1063,7 +1037,7 @@ def _process_args(self, *args, **kwargs):
10631037
"""
10641038
self.levels = args[0]
10651039
self.allsegs = args[1]
1066-
self.allkinds = len(args) > 2 and args[2] or None
1040+
self.allkinds = args[2] if len(args) > 2 else None
10671041
self.zmax = np.max(self.levels)
10681042
self.zmin = np.min(self.levels)
10691043

lib/matplotlib/transforms.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1529,33 +1529,27 @@ def transform_angles(self, angles, pts, radians=False, pushoff=1e-5):
15291529
# Must be 2D
15301530
if self.input_dims != 2 or self.output_dims != 2:
15311531
raise NotImplementedError('Only defined in 2D')
1532-
1533-
if pts.shape[1] != 2:
1534-
raise ValueError("'pts' must be array with 2 columns for x,y")
1535-
1532+
angles = np.asarray(angles)
1533+
pts = np.asarray(pts)
15361534
if angles.ndim != 1 or angles.shape[0] != pts.shape[0]:
15371535
raise ValueError("'angles' must be a column vector and have same "
15381536
"number of rows as 'pts'")
1539-
1537+
if pts.shape[1] != 2:
1538+
raise ValueError("'pts' must be array with 2 columns for x,y")
15401539
# Convert to radians if desired
15411540
if not radians:
1542-
angles = angles / 180.0 * np.pi
1543-
1541+
angles = np.deg2rad(angles)
15441542
# Move a short distance away
15451543
pts2 = pts + pushoff * np.c_[np.cos(angles), np.sin(angles)]
1546-
15471544
# Transform both sets of points
15481545
tpts = self.transform(pts)
15491546
tpts2 = self.transform(pts2)
1550-
15511547
# Calculate transformed angles
15521548
d = tpts2 - tpts
15531549
a = np.arctan2(d[:, 1], d[:, 0])
1554-
15551550
# Convert back to degrees if desired
15561551
if not radians:
15571552
a = np.rad2deg(a)
1558-
15591553
return a
15601554

15611555
def inverted(self):

0 commit comments

Comments
 (0)