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

Skip to content

Commit b48356f

Browse files
committed
Deprecate {ContourSet,Quiver}.ax in favor of .axes.
For consistency with other artists. In particular, Colorbar.remove assumes that the `.axes` attribute exists. Also a smattering of cleanups.
1 parent c080824 commit b48356f

File tree

3 files changed

+69
-73
lines changed

3 files changed

+69
-73
lines changed

doc/api/next_api_changes/deprecations.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,3 +395,8 @@ This method is deprecated. Use the ``GridSpec.nrows``, ``GridSpec.ncols``,
395395
Qt4-based backends
396396
~~~~~~~~~~~~~~~~~~
397397
The qt4agg and qt4cairo backends are deprecated.
398+
399+
``ContourSet.ax``, ``Quiver.ax``
400+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
401+
These attributes are deprecated in favor of ``ContourSet.axes`` and
402+
``Quiver.axes``, for consistency with other artists.

lib/matplotlib/contour.py

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ def set_label_props(self, label, text, color):
264264
label.set_text(text)
265265
label.set_color(color)
266266
label.set_fontproperties(self.labelFontProps)
267-
label.set_clip_box(self.ax.bbox)
267+
label.set_clip_box(self.axes.bbox)
268268

269269
def get_text(self, lev, fmt):
270270
"""Get the text of the label."""
@@ -404,7 +404,7 @@ def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5):
404404
return rotation, nlc
405405

406406
def _get_label_text(self, x, y, rotation):
407-
dx, dy = self.ax.transData.inverted().transform((x, y))
407+
dx, dy = self.axes.transData.inverted().transform((x, y))
408408
t = text.Text(dx, dy, rotation=rotation,
409409
horizontalalignment='center',
410410
verticalalignment='center', zorder=self._clabel_zorder)
@@ -415,7 +415,7 @@ def _get_label_clabeltext(self, x, y, rotation):
415415
# the data coordinate and create a label using ClabelText
416416
# class. This way, the rotation of the clabel is along the
417417
# contour line always.
418-
transDataInv = self.ax.transData.inverted()
418+
transDataInv = self.axes.transData.inverted()
419419
dx, dy = transDataInv.transform((x, y))
420420
drotation = transDataInv.transform_angles(np.array([rotation]),
421421
np.array([[x, y]]))
@@ -435,7 +435,7 @@ def _add_label(self, t, x, y, lev, cvalue):
435435
self.labelXYs.append((x, y))
436436

437437
# Add label to plot here - useful for manual mode label selection
438-
self.ax.add_artist(t)
438+
self.axes.add_artist(t)
439439

440440
def add_label(self, x, y, rotation, lev, cvalue):
441441
"""
@@ -479,7 +479,7 @@ def add_label_near(self, x, y, inline=True, inline_spacing=5,
479479
"""
480480

481481
if transform is None:
482-
transform = self.ax.transData
482+
transform = self.axes.transData
483483

484484
if transform:
485485
x, y = transform.transform((x, y))
@@ -498,7 +498,7 @@ def add_label_near(self, x, y, inline=True, inline_spacing=5,
498498
# grab its vertices
499499
lc = active_path.vertices
500500
# sort out where the new vertex should be added data-units
501-
xcmin = self.ax.transData.inverted().transform([xmin, ymin])
501+
xcmin = self.axes.transData.inverted().transform([xmin, ymin])
502502
# if there isn't a vertex close enough
503503
if not np.allclose(xcmin, lc[imin]):
504504
# insert new data into the vertex list
@@ -514,13 +514,13 @@ def add_label_near(self, x, y, inline=True, inline_spacing=5,
514514
lc = paths[segmin].vertices
515515

516516
# In pixel/screen space
517-
slc = self.ax.transData.transform(lc)
517+
slc = self.axes.transData.transform(lc)
518518

519519
# Get label width for rotating labels and breaking contours
520520
lw = self.get_label_width(self.labelLevelList[lmin],
521521
self.labelFmt, self.labelFontSizeList[lmin])
522522
# lw is in points.
523-
lw *= self.ax.figure.dpi / 72.0 # scale to screen coordinates
523+
lw *= self.axes.figure.dpi / 72 # scale to screen coordinates
524524
# now lw in pixels
525525

526526
# Figure out label rotation.
@@ -559,7 +559,7 @@ def labels(self, inline, inline_spacing):
559559
con = self.collections[icon]
560560
trans = con.get_transform()
561561
lw = self.get_label_width(lev, self.labelFmt, fsize)
562-
lw *= self.ax.figure.dpi / 72.0 # scale to screen coordinates
562+
lw *= self.axes.figure.dpi / 72 # scale to screen coordinates
563563
additions = []
564564
paths = con.get_paths()
565565
for segNum, linepath in enumerate(paths):
@@ -776,7 +776,7 @@ def __init__(self, ax, *args,
776776
Keyword arguments are as described in the docstring of
777777
`~.Axes.contour`.
778778
"""
779-
self.ax = ax
779+
self.axes = ax
780780
self.levels = levels
781781
self.filled = filled
782782
self.linewidths = linewidths
@@ -892,7 +892,7 @@ def __init__(self, ax, *args,
892892
alpha=self.alpha,
893893
transform=self.get_transform(),
894894
zorder=self._contour_zorder)
895-
self.ax.add_collection(col, autolim=False)
895+
self.axes.add_collection(col, autolim=False)
896896
self.collections.append(col)
897897
else:
898898
tlinewidths = self._process_linewidths()
@@ -914,14 +914,14 @@ def __init__(self, ax, *args,
914914
transform=self.get_transform(),
915915
zorder=self._contour_zorder)
916916
col.set_label('_nolegend_')
917-
self.ax.add_collection(col, autolim=False)
917+
self.axes.add_collection(col, autolim=False)
918918
self.collections.append(col)
919919

920920
for col in self.collections:
921921
col.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
922922
col.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
923-
self.ax.update_datalim([self._mins, self._maxs])
924-
self.ax.autoscale_view(tight=True)
923+
self.axes.update_datalim([self._mins, self._maxs])
924+
self.axes.autoscale_view(tight=True)
925925

926926
self.changed() # set the colors
927927

@@ -930,16 +930,21 @@ def __init__(self, ax, *args,
930930
cbook._warn_external('The following kwargs were not used by '
931931
'contour: ' + s)
932932

933+
@cbook.deprecated("3.3")
934+
@property
935+
def ax(self):
936+
return self.axes
937+
933938
def get_transform(self):
934939
"""
935940
Return the :class:`~matplotlib.transforms.Transform`
936941
instance used by this ContourSet.
937942
"""
938943
if self._transform is None:
939-
self._transform = self.ax.transData
944+
self._transform = self.axes.transData
940945
elif (not isinstance(self._transform, mtransforms.Transform)
941946
and hasattr(self._transform, '_as_mpl_transform')):
942-
self._transform = self._transform._as_mpl_transform(self.ax)
947+
self._transform = self._transform._as_mpl_transform(self.axes)
943948
return self._transform
944949

945950
def __getstate__(self):
@@ -1435,9 +1440,9 @@ def _process_args(self, *args, corner_mask=None, **kwargs):
14351440

14361441
# if the transform is not trans data, and some part of it
14371442
# contains transData, transform the xs and ys to data coordinates
1438-
if (t != self.ax.transData and
1439-
any(t.contains_branch_seperately(self.ax.transData))):
1440-
trans_to_data = t - self.ax.transData
1443+
if (t != self.axes.transData and
1444+
any(t.contains_branch_seperately(self.axes.transData))):
1445+
trans_to_data = t - self.axes.transData
14411446
pts = np.vstack([x.flat, y.flat]).T
14421447
transformed_pts = trans_to_data.transform(pts)
14431448
x = transformed_pts[..., 0]
@@ -1502,9 +1507,9 @@ def _check_xyz(self, args, kwargs):
15021507
convert them to 2D using meshgrid.
15031508
"""
15041509
x, y = args[:2]
1505-
kwargs = self.ax._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
1506-
x = self.ax.convert_xunits(x)
1507-
y = self.ax.convert_yunits(y)
1510+
kwargs = self.axes._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
1511+
x = self.axes.convert_xunits(x)
1512+
y = self.axes.convert_yunits(y)
15081513

15091514
x = np.asarray(x, dtype=np.float64)
15101515
y = np.asarray(y, dtype=np.float64)

lib/matplotlib/quiver.py

Lines changed: 37 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def __init__(self, Q, X, Y, U, label,
259259
self.color = color
260260
self.label = label
261261
self._labelsep_inches = labelsep
262-
self.labelsep = (self._labelsep_inches * Q.ax.figure.dpi)
262+
self.labelsep = (self._labelsep_inches * Q.axes.figure.dpi)
263263

264264
# try to prevent closure over the real self
265265
weak_self = weakref.ref(self)
@@ -272,8 +272,8 @@ def on_dpi_change(fig):
272272
# the start of draw.
273273
self_weakref._initialized = False
274274

275-
self._cid = Q.ax.figure.callbacks.connect('dpi_changed',
276-
on_dpi_change)
275+
self._cid = Q.axes.figure.callbacks.connect(
276+
'dpi_changed', on_dpi_change)
277277

278278
self.labelpos = labelpos
279279
self.labelcolor = labelcolor
@@ -293,13 +293,10 @@ def on_dpi_change(fig):
293293
self.zorder = Q.zorder + 0.1
294294

295295
def remove(self):
296-
"""
297-
Overload the remove method
298-
"""
299-
self.Q.ax.figure.callbacks.disconnect(self._cid)
296+
# docstring inherited
297+
self.Q.axes.figure.callbacks.disconnect(self._cid)
300298
self._cid = None
301-
# pass the remove call up the stack
302-
martist.Artist.remove(self)
299+
super().remove() # pass the remove call up the stack
303300

304301
def _init(self):
305302
if True: # not self._initialized:
@@ -355,16 +352,12 @@ def draw(self, renderer):
355352
self.stale = False
356353

357354
def _set_transform(self):
358-
if self.coord == 'data':
359-
self.set_transform(self.Q.ax.transData)
360-
elif self.coord == 'axes':
361-
self.set_transform(self.Q.ax.transAxes)
362-
elif self.coord == 'figure':
363-
self.set_transform(self.Q.ax.figure.transFigure)
364-
elif self.coord == 'inches':
365-
self.set_transform(self.Q.ax.figure.dpi_scale_trans)
366-
else:
367-
raise ValueError('unrecognized coordinates')
355+
self.set_transform(cbook._check_getitem({
356+
"data": self.Q.axes.transData,
357+
"axes": self.Q.axes.transAxes,
358+
"figure": self.Q.axes.figure.transFigure,
359+
"inches": self.Q.axes.figure.dpi_scale_trans,
360+
}, coordinates=self.coord))
368361

369362
def set_figure(self, fig):
370363
martist.Artist.set_figure(self, fig)
@@ -477,7 +470,7 @@ def __init__(self, ax, *args,
477470
by the following pyplot interface documentation:
478471
%s
479472
"""
480-
self.ax = ax
473+
self._axes = ax # The attr actually set by the Artist.axes property.
481474
X, Y, U, V, C = _parse_args(*args, caller_name='quiver()')
482475
self.X = X
483476
self.Y = Y
@@ -510,8 +503,7 @@ def __init__(self, ax, *args,
510503
self.set_UVC(U, V, C)
511504
self._initialized = False
512505

513-
# try to prevent closure over the real self
514-
weak_self = weakref.ref(self)
506+
weak_self = weakref.ref(self) # Prevent closure over the real self.
515507

516508
def on_dpi_change(fig):
517509
self_weakref = weak_self()
@@ -522,18 +514,17 @@ def on_dpi_change(fig):
522514
# the start of draw.
523515
self_weakref._initialized = False
524516

525-
self._cid = self.ax.figure.callbacks.connect('dpi_changed',
526-
on_dpi_change)
517+
self._cid = ax.figure.callbacks.connect('dpi_changed', on_dpi_change)
518+
519+
@cbook.deprecated("3.3", alternative="axes")
520+
def ax(self):
521+
return self.axes
527522

528523
def remove(self):
529-
"""
530-
Overload the remove method
531-
"""
532-
# disconnect the call back
533-
self.ax.figure.callbacks.disconnect(self._cid)
524+
# docstring inherited
525+
self.axes.figure.callbacks.disconnect(self._cid)
534526
self._cid = None
535-
# pass the remove call up the stack
536-
mcollections.PolyCollection.remove(self)
527+
super().remove() # pass the remove call up the stack
537528

538529
def _init(self):
539530
"""
@@ -544,8 +535,7 @@ def _init(self):
544535
# available to have this work on an as-needed basis at present.
545536
if True: # not self._initialized:
546537
trans = self._set_transform()
547-
ax = self.ax
548-
self.span = trans.inverted().transform_bbox(ax.bbox).width
538+
self.span = trans.inverted().transform_bbox(self.axes.bbox).width
549539
if self.width is None:
550540
sn = np.clip(math.sqrt(self.N), 8, 25)
551541
self.width = 0.06 * self.span / sn
@@ -606,31 +596,30 @@ def _dots_per_unit(self, units):
606596
"""
607597
Return a scale factor for converting from units to pixels
608598
"""
609-
ax = self.ax
610599
if units in ('x', 'y', 'xy'):
611600
if units == 'x':
612-
dx0 = ax.viewLim.width
613-
dx1 = ax.bbox.width
601+
dx0 = self.axes.viewLim.width
602+
dx1 = self.axes.bbox.width
614603
elif units == 'y':
615-
dx0 = ax.viewLim.height
616-
dx1 = ax.bbox.height
604+
dx0 = self.axes.viewLim.height
605+
dx1 = self.axes.bbox.height
617606
else: # 'xy' is assumed
618-
dxx0 = ax.viewLim.width
619-
dxx1 = ax.bbox.width
620-
dyy0 = ax.viewLim.height
621-
dyy1 = ax.bbox.height
607+
dxx0 = self.axes.viewLim.width
608+
dxx1 = self.axes.bbox.width
609+
dyy0 = self.axes.viewLim.height
610+
dyy1 = self.axes.bbox.height
622611
dx1 = np.hypot(dxx1, dyy1)
623612
dx0 = np.hypot(dxx0, dyy0)
624613
dx = dx1 / dx0
625614
else:
626615
if units == 'width':
627-
dx = ax.bbox.width
616+
dx = self.axes.bbox.width
628617
elif units == 'height':
629-
dx = ax.bbox.height
618+
dx = self.axes.bbox.height
630619
elif units == 'dots':
631620
dx = 1.0
632621
elif units == 'inches':
633-
dx = ax.figure.dpi
622+
dx = self.axes.figure.dpi
634623
else:
635624
raise ValueError('unrecognized units')
636625
return dx
@@ -647,9 +636,9 @@ def _set_transform(self):
647636
return trans
648637

649638
def _angles_lengths(self, U, V, eps=1):
650-
xy = self.ax.transData.transform(self.XY)
639+
xy = self.axes.transData.transform(self.XY)
651640
uv = np.column_stack((U, V))
652-
xyp = self.ax.transData.transform(self.XY + eps * uv)
641+
xyp = self.axes.transData.transform(self.XY + eps * uv)
653642
dxy = xyp - xy
654643
angles = np.arctan2(dxy[:, 1], dxy[:, 0])
655644
lengths = np.hypot(*dxy.T) / eps
@@ -667,7 +656,7 @@ def _make_verts(self, U, V, angles):
667656
# Calculate eps based on the extents of the plot
668657
# so that we don't end up with roundoff error from
669658
# adding a small number to a large.
670-
eps = np.abs(self.ax.dataLim.extents).max() * 0.001
659+
eps = np.abs(self.axes.dataLim.extents).max() * 0.001
671660
angles, lengths = self._angles_lengths(U, V, eps=eps)
672661
if str_angles and self.scale_units == 'xy':
673662
a = lengths
@@ -803,7 +792,6 @@ def _h_arrows(self, length):
803792
: / \ \ \
804793
: ------------------------------
805794
806-
807795
The largest increment is given by a triangle (or "flag"). After those
808796
come full lines (barbs). The smallest increment is a half line. There
809797
is only, of course, ever at most 1 half line. If the magnitude is
@@ -815,8 +803,6 @@ def _h_arrows(self, length):
815803
816804
See also https://en.wikipedia.org/wiki/Wind_barb.
817805
818-
819-
820806
Parameters
821807
----------
822808
X, Y : 1D or 2D array-like, optional

0 commit comments

Comments
 (0)