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 65360f5

Browse filesBrowse files
committed
Remove redundant iteration through Axes._children.
Note, that the legend `test_fancy` test needed an ordering change because legends handles are no longer grouped by type.
1 parent 1ed85e7 commit 65360f5
Copy full SHA for 65360f5

File tree

Expand file treeCollapse file tree

4 files changed

+72
-54
lines changed
Filter options
Expand file treeCollapse file tree

4 files changed

+72
-54
lines changed

‎lib/matplotlib/axes/_base.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_base.py
+16-18Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1920,10 +1920,13 @@ def _sci(self, im):
19201920
`~.pyplot.viridis`, and other functions such as `~.pyplot.clim`. The
19211921
current image is an attribute of the current axes.
19221922
"""
1923+
cbook._check_isinstance(
1924+
(mpl.contour.ContourSet, mcoll.Collection, mimage.AxesImage),
1925+
im=im)
19231926
if isinstance(im, mpl.contour.ContourSet):
1924-
if im.collections[0] not in self.collections:
1927+
if im.collections[0] not in self._children:
19251928
raise ValueError("ContourSet must be in current Axes")
1926-
elif im not in self.images and im not in self.collections:
1929+
elif im not in self._children:
19271930
raise ValueError("Argument must be an image, collection, or "
19281931
"ContourSet in this Axes")
19291932
self._current_image = im
@@ -1940,11 +1943,9 @@ def has_data(self):
19401943
need to be updated, and may not actually be useful for
19411944
anything.
19421945
"""
1943-
return (
1944-
len(self.collections) +
1945-
len(self.images) +
1946-
len(self.lines) +
1947-
len(self.patches)) > 0
1946+
return any(isinstance(a, (mcoll.Collection, mimage.AxesImage,
1947+
mlines.Line2D, mpatches.Patch))
1948+
for a in self._children)
19481949

19491950
def add_artist(self, a):
19501951
"""
@@ -2182,17 +2183,14 @@ def relim(self, visible_only=False):
21822183
self.dataLim.set_points(mtransforms.Bbox.null().get_points())
21832184
self.ignore_existing_data_limits = True
21842185

2185-
for line in self.lines:
2186-
if not visible_only or line.get_visible():
2187-
self._update_line_limits(line)
2188-
2189-
for p in self.patches:
2190-
if not visible_only or p.get_visible():
2191-
self._update_patch_limits(p)
2192-
2193-
for image in self.images:
2194-
if not visible_only or image.get_visible():
2195-
self._update_image_limits(image)
2186+
for artist in self._children:
2187+
if not visible_only or artist.get_visible():
2188+
if isinstance(artist, mlines.Line2D):
2189+
self._update_line_limits(artist)
2190+
elif isinstance(artist, mpatches.Patch):
2191+
self._update_patch_limits(artist)
2192+
elif isinstance(artist, mimage.AxesImage):
2193+
self._update_image_limits(artist)
21962194

21972195
def update_datalim(self, xys, updatex=True, updatey=True):
21982196
"""

‎lib/matplotlib/legend.py

Copy file name to clipboardExpand all lines: lib/matplotlib/legend.py
+27-18Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@
3535
from matplotlib.lines import Line2D
3636
from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch,
3737
StepPatch)
38-
from matplotlib.collections import (LineCollection, RegularPolyCollection,
39-
CircleCollection, PathCollection,
40-
PolyCollection)
38+
from matplotlib.collections import (
39+
Collection, CircleCollection, LineCollection, PathCollection,
40+
PolyCollection, RegularPolyCollection)
4141
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
4242
from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
4343

@@ -826,18 +826,23 @@ def _auto_legend_data(self):
826826
List of (x, y) offsets of all collection.
827827
"""
828828
assert self.isaxes # always holds, as this is only called internally
829-
ax = self.parent
830-
lines = [line.get_transform().transform_path(line.get_path())
831-
for line in ax.lines]
832-
bboxes = [patch.get_bbox().transformed(patch.get_data_transform())
833-
if isinstance(patch, Rectangle) else
834-
patch.get_path().get_extents(patch.get_transform())
835-
for patch in ax.patches]
829+
bboxes = []
830+
lines = []
836831
offsets = []
837-
for handle in ax.collections:
838-
_, transOffset, hoffsets, _ = handle._prepare_points()
839-
for offset in transOffset.transform(hoffsets):
840-
offsets.append(offset)
832+
for artist in self.parent._children:
833+
if isinstance(artist, Line2D):
834+
lines.append(
835+
artist.get_transform().transform_path(artist.get_path()))
836+
elif isinstance(artist, Rectangle):
837+
bboxes.append(
838+
artist.get_bbox().transformed(artist.get_data_transform()))
839+
elif isinstance(artist, Patch):
840+
bboxes.append(
841+
artist.get_path().get_extents(artist.get_transform()))
842+
elif isinstance(artist, Collection):
843+
_, transOffset, hoffsets, _ = artist._prepare_points()
844+
for offset in transOffset.transform(hoffsets):
845+
offsets.append(offset)
841846
return bboxes, lines, offsets
842847

843848
def get_children(self):
@@ -1114,13 +1119,17 @@ def _get_legend_handles(axs, legend_handler_map=None):
11141119
"""
11151120
handles_original = []
11161121
for ax in axs:
1117-
handles_original += [*ax.lines, *ax.patches, *ax.collections,
1118-
*ax.containers]
1122+
handles_original += [
1123+
*(a for a in ax._children
1124+
if isinstance(a, (Line2D, Patch, Collection))),
1125+
*ax.containers]
11191126
# support parasite axes:
11201127
if hasattr(ax, 'parasites'):
11211128
for axx in ax.parasites:
1122-
handles_original += [*axx.lines, *axx.patches,
1123-
*axx.collections, *axx.containers]
1129+
handles_original += [
1130+
*(a for a in axx._children
1131+
if isinstance(a, (Line2D, Patch, Collection))),
1132+
*axx.containers]
11241133

11251134
handler_map = Legend.get_default_handler_map()
11261135

‎lib/matplotlib/tests/test_legend.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_legend.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ def test_alpha_rcparam():
126126
def test_fancy():
127127
# using subplot triggers some offsetbox functionality untested elsewhere
128128
plt.subplot(121)
129-
plt.scatter(np.arange(10), np.arange(10, 0, -1), label='XX\nXX')
130129
plt.plot([5] * 10, 'o--', label='XX')
130+
plt.scatter(np.arange(10), np.arange(10, 0, -1), label='XX\nXX')
131131
plt.errorbar(np.arange(10), np.arange(10), xerr=0.5,
132132
yerr=0.5, label='XX')
133133
plt.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],

‎lib/mpl_toolkits/mplot3d/axes3d.py

Copy file name to clipboardExpand all lines: lib/mpl_toolkits/mplot3d/axes3d.py
+28-17Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,16 @@
1919

2020
import numpy as np
2121

22-
from matplotlib import artist
2322
from matplotlib import _api
23+
import matplotlib.artist as martist
2424
import matplotlib.axes as maxes
2525
import matplotlib.cbook as cbook
2626
import matplotlib.collections as mcoll
2727
import matplotlib.colors as mcolors
2828
import matplotlib.docstring as docstring
29+
import matplotlib.image as mimage
30+
import matplotlib.lines as mlines
31+
import matplotlib.patches as mpatches
2932
import matplotlib.scale as mscale
3033
import matplotlib.container as mcontainer
3134
import matplotlib.transforms as mtransforms
@@ -376,7 +379,7 @@ def apply_aspect(self, position=None):
376379
pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect)
377380
self._set_position(pb1.anchored(self.get_anchor(), pb), 'active')
378381

379-
@artist.allow_rasterization
382+
@martist.allow_rasterization
380383
def draw(self, renderer):
381384
# draw the background patch
382385
self.patch.draw(renderer)
@@ -440,16 +443,19 @@ def do_3d_projection(artist):
440443
# Make sure they are drawn above the grids.
441444
zorder_offset = max(axis.get_zorder()
442445
for axis in self._get_axis_list()) + 1
443-
for i, col in enumerate(
444-
sorted(self.collections,
445-
key=do_3d_projection,
446-
reverse=True)):
447-
col.zorder = zorder_offset + i
448-
for i, patch in enumerate(
449-
sorted(self.patches,
450-
key=do_3d_projection,
451-
reverse=True)):
452-
patch.zorder = zorder_offset + i
446+
collections_and_patches = (
447+
a for a in self._children
448+
if isinstance(a, (mcoll.Collection, mpatches.Patch)))
449+
collection_count = patch_count = 0
450+
for artist in sorted(collections_and_patches,
451+
key=do_3d_projection,
452+
reverse=True):
453+
if isinstance(artist, mcoll.Collection):
454+
artist.zorder = zorder_offset + collection_count
455+
collection_count += 1
456+
elif isinstance(artist, mpatches.Patch):
457+
artist.zorder = zorder_offset + patch_count
458+
patch_count += 1
453459

454460
if self._axis3don:
455461
# Draw panes first
@@ -674,10 +680,15 @@ def autoscale_view(self, tight=None, scalex=True, scaley=True,
674680
# This method looks at the rectangular volume (see above)
675681
# of data and decides how to scale the view portal to fit it.
676682
if tight is None:
677-
# if image data only just use the datalim
678-
_tight = self._tight or (
679-
len(self.images) > 0
680-
and len(self.lines) == len(self.patches) == 0)
683+
_tight = self._tight
684+
if not _tight:
685+
# if image data only just use the datalim
686+
for artist in self._children:
687+
if isinstance(artist, mimage.AxesImage):
688+
_tight = True
689+
elif isinstance(artist, (mlines.Line2D, mpatches.Patch)):
690+
_tight = False
691+
break
681692
else:
682693
_tight = self._tight = bool(tight)
683694

@@ -3288,7 +3299,7 @@ def get_tightbbox(self, renderer, call_axes_locator=True,
32883299
batch.append(axis_bb)
32893300
return mtransforms.Bbox.union(batch)
32903301

3291-
docstring.interpd.update(Axes3D_kwdoc=artist.kwdoc(Axes3D))
3302+
docstring.interpd.update(Axes3D_kwdoc=martist.kwdoc(Axes3D))
32923303
docstring.dedent_interpd(Axes3D.__init__)
32933304

32943305

0 commit comments

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