"""rightorder: draw Matplotlib 3D plots with hidden parts hidden. import rightorder rightorder.fix(ax) # a 3D axes, or a whole figure Matplotlib's mplot3d paints each object as one layer, so surfaces that cross are drawn with one wholly on top. This cuts faces, lines and points where face planes cross them (a binary space partition, an old and well known method), then paints the pieces from back to front. The output is still ordinary vector drawing. Covers surfaces and other face collections (plot_surface, plot_trisurf, bar3d, voxels, Poly3DCollection, contour, contourf), lines (plot, plot_wireframe, contour, line collections) and scatter points. Text and legends stay on top. 2D patches placed in 3D are left to Matplotlib, with a warning. Tested with Matplotlib 3.11.2. It reads private parts of mplot3d, so other versions may break it. MIT licence. No dependencies beyond Matplotlib and NumPy. """ import warnings import numpy as np from matplotlib import colors as mcolors from matplotlib.collections import PathCollection from matplotlib.path import Path from matplotlib.transforms import IdentityTransform from mpl_toolkits.mplot3d import art3d, axes3d, proj3d __version__ = "1.0" __all__ = ["fix", "unfix"] # Lengths below are fractions of the scene's width in each direction. On a plot 700 pixels wide, 0.001 is # less than a pixel. # (how near a plane counts as on it, how far from flat a face may be and stay in one piece) _SOLID = (4e-4, 1e-3) # See-through shapes show what is behind them, so a small error in order is easier to see: tighter, and slower. _CLEAR = (5e-5, 1e-4) _STEP_PX = 2.5 # lines are tested for visibility in pieces no longer than this _SEAM_PT = 0.35 # outline in its own colour, to cover hairline cracks between opaque pieces _MAX_PIECES = 400_000 _POLY, _LINE, _POINT = 0, 1, 2 # ------------------------------------------------------------------ collecting what to draw class _Style: """How one piece is painted. Pieces cut from the same shape share it.""" __slots__ = ("kind", "face", "edge", "width", "dash", "aa", "group", "marker", "size", "source", "seam") def __init__(self, kind, face=(0, 0, 0, 0), edge=(0, 0, 0, 0), width=0.0, dash=(0, None), aa=True, group=0, marker=None, size=1.0, source=None, seam=True): self.kind, self.face, self.edge, self.width, self.dash, self.aa = kind, face, edge, width, dash, aa self.group, self.marker, self.size, self.source, self.seam = group, marker, size, source, seam def _scaled(points, ax): """Apply the axes' scales (log and so on). Returns an (n, 3) float array with NaN for unusable points.""" p = np.ma.asanyarray(points, dtype=float).reshape(-1, 3) p = np.ma.filled(p, np.nan) if len(p) == 0: return p with np.errstate(all="ignore"): out = np.column_stack([np.ma.filled(np.ma.asanyarray(c, dtype=float), np.nan) for c in proj3d._apply_scale_transforms(p[:, 0], p[:, 1], p[:, 2], ax)]) out[~np.isfinite(out).all(axis=1)] = np.nan return out def _outside_limits(points, ax): """Which data points fall outside the view limits (used only when the artist asked for clipping).""" p = np.ma.filled(np.ma.asanyarray(points, dtype=float), np.nan).reshape(-1, 3) lims = (ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()) bad = np.zeros(len(p), bool) for k, (a, b) in enumerate(lims): lo, hi = min(a, b), max(a, b) bad |= ~((p[:, k] >= lo) & (p[:, k] <= hi)) return bad def _pick(seq, i): return seq[i % len(seq)] def _same_colour(a, b): return np.allclose(a, b, atol=1 / 255) def _add_lines(items, ax, xyz, style, clip): pts = _scaled(xyz, ax) if clip and len(pts): pts[_outside_limits(xyz, ax)] = np.nan ok = ~np.isnan(pts).any(axis=1) for i in range(len(pts) - 1): if ok[i] and ok[i + 1]: items.append((_LINE, [pts[i:i + 2]], style)) def _gather_polys(items, ax, col, group): if col._A is not None: col.update_scalarmappable() if col._face_is_mapped: col._facecolor3d = col._facecolors if col._edge_is_mapped: col._edgecolor3d = col._edgecolors faces = col._faces n = len(faces) if n == 0: return invalid = np.broadcast_to(col._invalid_vertices, faces.shape[:2]) fc = mcolors.to_rgba_array(col._facecolor3d) ec = col._edgecolor3d ec = mcolors.to_rgba_array(ec) if len(ec) else np.zeros((0, 4)) widths = np.atleast_1d(col.get_linewidth()) dashes = col._linestyles codes = col._codes3d scaled = _scaled(faces.reshape(-1, 3), ax).reshape(faces.shape) for i in range(n): keep = ~invalid[i] raw = scaled[i][keep] if len(raw) < 2 or np.isnan(raw).any(): continue if col._axlim_clip and _outside_limits(faces[i][keep], ax).any(): continue face = tuple(_pick(fc, i)) if len(fc) else (0, 0, 0, 0) edge = tuple(_pick(ec, i)) if len(ec) else (0, 0, 0, 0) width = float(_pick(widths, i)) if len(widths) else 0.0 if codes is not None and len(codes): # A compound path: several rings, possibly holes, all in one plane. code = np.asarray(codes[i])[: len(keep)][keep[: len(codes[i])]] starts = [k for k, c in enumerate(code) if c == Path.MOVETO] or [0] rings = [raw[a:b] for a, b in zip(starts, starts[1:] + [len(raw)])] rings = [r[:-1] if len(r) > 1 and code[a + len(r) - 1] == Path.CLOSEPOLY else r for r, a in zip(rings, starts)] else: rings = [raw] rings = [_dedupe(r) for r in rings] outline = width > 0 and edge[3] > 0 # An edge in the face's own colour is only there to hide cracks. Treat it as part of the face. distinct = outline and not (face[3] > 0 and _same_colour(face, edge)) if face[3] > 0: style = _Style(_POLY, face=face, group=group, aa=True) pieces = [r for r in rings if len(r) >= 3] if pieces: items.append((_POLY, pieces, style)) if distinct: dash = _pick(dashes, i) if dashes else (0, None) line_style = _Style(_LINE, edge=edge, width=width, dash=dash, group=group) for r in rings: closed = np.vstack([r, r[:1]]) if len(r) > 2 else r for a in range(len(closed) - 1): items.append((_LINE, [closed[a:a + 2]], line_style)) def _dedupe(r): if len(r) < 2: return r keep = np.any(np.abs(r - np.roll(r, 1, axis=0)) > 0, axis=1) return r[keep] if keep.any() else r[:1] def _newell(r): q = np.roll(r, -1, axis=0) d, s = r - q, r + q return np.array([np.dot(d[:, 1], s[:, 2]), np.dot(d[:, 2], s[:, 0]), np.dot(d[:, 0], s[:, 1])]) def _off_plane(pts): """How far the farthest corner lies from the best-fitting plane.""" q = pts - pts.mean(axis=0) _, vectors = np.linalg.eigh(q.T @ q) return np.abs(q @ vectors[:, 0]).max() def _flat_parts(ring, flat_to, depth=0): """Cut a face that is not flat into as few nearly flat convex parts as is easy to find.""" n = len(ring) if n == 3 or _off_plane(ring) <= flat_to: return [ring] if n > 3 and depth < 12 and _is_convex(ring): half = n // 2 best, best_error = None, np.inf for start in range(half if n % 2 == 0 else n): turned = np.concatenate([ring[start:], ring[:start]]) one, two = turned[:half + 1], np.concatenate([turned[half:], turned[:1]]) error = max(_off_plane(one) if len(one) > 3 else 0.0, _off_plane(two) if len(two) > 3 else 0.0) if error < best_error: best, best_error = (one, two), error return _flat_parts(best[0], flat_to, depth + 1) + _flat_parts(best[1], flat_to, depth + 1) return _triangulate(ring) def _is_convex(ring): edge = np.concatenate([ring[1:], ring[:1]]) - ring nxt = np.concatenate([edge[1:], edge[:1]]) x, y, z = edge.T u, v, w = nxt.T turns = np.stack([y * w - z * v, z * u - x * w, x * v - y * u], 1) return bool((turns @ _newell(ring) >= -1e-14).all()) def _clearly_concave(ring): """Whether some corner turns inwards by more than about 12 degrees. Curved surfaces give faces with corners that are very slightly inwards; cutting those leaves no joining edge worth worrying about.""" edge = np.concatenate([ring[1:], ring[:1]]) - ring edge = edge[np.linalg.norm(edge, axis=1) > 1e-9] if len(edge) < 4: return False nxt = np.concatenate([edge[1:], edge[:1]]) normal = _newell(ring) size = np.linalg.norm(normal) * np.linalg.norm(edge, axis=1) * np.linalg.norm(nxt, axis=1) if not size.all(): return True x, y, z = edge.T u, v, w = nxt.T turns = np.stack([y * w - z * v, z * u - x * w, x * v - y * u], 1) return bool((turns @ normal / size < -0.2).any()) def _flatten(items, flat_to): """Replace faces that are not flat with flat parts. `items` are in scene coordinates.""" wanted = [i for i, (kind, rings, _) in enumerate(items) if kind == _POLY and len(rings) == 1 and len(rings[0]) > 3] # test faces with the same number of corners together flat = {} by_size = {} for i in wanted: by_size.setdefault(len(items[i][1][0]), []).append(i) for members in by_size.values(): stack = np.array([items[i][1][0] for i in members]) q = stack - stack.mean(axis=1, keepdims=True) _, vectors = np.linalg.eigh(np.einsum("nki,nkj->nij", q, q)) off = np.abs(np.einsum("nki,ni->nk", q, vectors[:, :, 0])).max(axis=1) flat.update(zip(members, off <= flat_to)) out = [] for i, (kind, rings, style) in enumerate(items): if kind == _POLY and style.seam and (len(rings) > 1 or ( len(rings[0]) > 3 and flat.get(i, True) and _clearly_concave(rings[0]))): style = _Style(_POLY, face=style.face, group=style.group, seam=False) if i in flat and not flat[i]: out.extend((kind, [part], style) for part in _flat_parts(rings[0], flat_to)) else: out.append((kind, rings, style)) return out def _triangulate(r): """Ear clipping in the ring's average plane. For a face whose corners are not in one plane.""" n = len(r) if n == 3: return [r] normal = _newell(r) drop = int(np.argmax(np.abs(normal))) a, b = [k for k in range(3) if k != drop] p = r[:, [a, b]].copy() area = np.dot(p[:, 0], np.roll(p[:, 1], -1)) - np.dot(p[:, 1], np.roll(p[:, 0], -1)) sign = 1.0 if area >= 0 else -1.0 idx = list(range(n)) out = [] def cross(o, u, v): return (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0]) while len(idx) > 3: best, best_q = None, -np.inf for k in range(len(idx)): i, j, m = idx[k - 1], idx[k], idx[(k + 1) % len(idx)] turn = sign * cross(p[i], p[j], p[m]) if turn <= 0: continue inside = False for t in idx: if t in (i, j, m): continue if (sign * cross(p[i], p[j], p[t]) > 0 and sign * cross(p[j], p[m], p[t]) > 0 and sign * cross(p[m], p[i], p[t]) > 0): inside = True break if inside: continue e = (np.sum((p[j] - p[i]) ** 2) + np.sum((p[m] - p[j]) ** 2) + np.sum((p[i] - p[m]) ** 2)) quality = turn / e if e else 0 if quality > best_q: best, best_q = k, quality if best is None: break out.append(r[[idx[best - 1], idx[best], idx[(best + 1) % len(idx)]]]) del idx[best] if len(idx) == 3: out.append(r[idx]) else: # ring crosses itself: fall back to a fan out.extend(r[[idx[0], idx[k], idx[k + 1]]] for k in range(1, len(idx) - 1)) return out def _rings_of_path(vertices, codes): """Split one compound path into [(ring, closed)]. `vertices` are (n, 3).""" if codes is None: return [(vertices, False)] codes = np.asarray(codes) starts = [k for k, c in enumerate(codes) if c == Path.MOVETO] or [0] out = [] for a, b in zip(starts, starts[1:] + [len(codes)]): closed = codes[b - 1] == Path.CLOSEPOLY out.append((vertices[a:b - 1] if closed else vertices[a:b], closed)) return out def _gather_contour_set(items, ax, col, group): """Contour lines and filled contours: compound paths, possibly with holes.""" col.update_scalarmappable() fc, ec = col.get_facecolor(), col.get_edgecolor() widths = np.atleast_1d(col.get_linewidth()) dashes = col._linestyles filled = getattr(col, "filled", len(fc) > 0) for i, (vertices, codes) in enumerate(col._3dverts_codes): if len(vertices) == 0: continue vertices = np.asarray(vertices, float) rings = [] for ring, closed in _rings_of_path(vertices, codes): points = _scaled(ring, ax) if col._axlim_clip and len(points): points[_outside_limits(ring, ax)] = np.nan rings.append((points, closed)) face = tuple(_pick(fc, i)) if len(fc) else (0, 0, 0, 0) if filled and face[3] > 0: solid = [_dedupe(r[~np.isnan(r).any(axis=1)]) for r, _ in rings] solid = [r for r in solid if len(r) >= 3] if solid: style = _Style(_POLY, face=face, group=group) every = np.vstack(solid) if len(solid) == 1 or _off_plane(every) <= 1e-9 * max(np.ptp(every), 1): items.append((_POLY, solid, style)) else: items.extend((_POLY, [r], style) for r in solid) edge = tuple(_pick(ec, i)) if len(ec) else (0, 0, 0, 0) width = float(_pick(widths, i)) if len(widths) else 0.0 if edge[3] > 0 and width > 0 and not (filled and _same_colour(face, edge)): style = _Style(_LINE, edge=edge, width=width, dash=_pick(dashes, i) if dashes else (0, None), group=group) for points, closed in rings: if closed and len(points): points = np.vstack([points, points[:1]]) for a in range(len(points) - 1): if not np.isnan(points[a:a + 2]).any(): items.append((_LINE, [points[a:a + 2]], style)) def _gather_line_collection(items, ax, col, group): segs = col._segments3d ec = col.get_edgecolor() widths = np.atleast_1d(col.get_linewidth()) dashes = col._linestyles fc = col.get_facecolor() for i, seg in enumerate(segs): if len(fc) and _pick(fc, i)[3] > 0: # a line collection may also fill each line's inside ring = _scaled(seg, ax) ring = _dedupe(ring[~np.isnan(ring).any(axis=1)]) if len(ring) >= 3: items.append((_POLY, [ring], _Style(_POLY, face=tuple(_pick(fc, i)), group=group))) if len(ec) == 0: continue style = _Style(_LINE, edge=tuple(_pick(ec, i)), width=float(_pick(widths, i)), dash=_pick(dashes, i) if dashes else (0, None), group=group) _add_lines(items, ax, seg, style, col._axlim_clip) def _marker_style(path, size, face, edge, width, group): return _Style(_POINT, face=face, edge=edge, width=width, marker=path, size=size, group=group) def _marked(every, n): """Which points get a marker, following Line2D's markevery for counts, slices and lists.""" index = np.arange(n) if every is None: return index if isinstance(every, (int, np.integer)): return index[::every] if isinstance(every, slice): return index[every] if isinstance(every, tuple) and len(every) == 2 and all(isinstance(v, (int, np.integer)) for v in every): return index[every[0]::every[1]] if isinstance(every, (list, np.ndarray)): return index[np.asarray(every)] if len(every) else index[:0] warnings.warn("rightorder: this markevery setting is not supported; every point is marked", stacklevel=2) return index def _gather_line3d(items, ax, line, group): xyz = np.column_stack([np.ma.filled(np.ma.asanyarray(c, dtype=float), np.nan).ravel() for c in np.broadcast_arrays(*[np.ma.asanyarray(v) for v in line.get_data_3d()])]) alpha = line.get_alpha() if line.get_linestyle() not in ("None", "none", " ", ""): style = _Style(_LINE, edge=mcolors.to_rgba(line.get_color(), alpha), width=line.get_linewidth(), dash=line._dash_pattern if line.is_dashed() else (0, None), group=group, aa=line.get_antialiased()) _add_lines(items, ax, xyz, style, line._axlim_clip) marker = line.get_marker() if marker not in (None, "None", "none", " ", ""): ms = line._marker path = ms.get_path().transformed(ms.get_transform()) face = line.get_markerfacecolor() face = (0, 0, 0, 0) if (isinstance(face, str) and face == "none") or not ms.is_filled() \ else mcolors.to_rgba(face, alpha) edge = mcolors.to_rgba(line.get_markeredgecolor(), alpha) style = _marker_style(path, line.get_markersize(), face, edge, line.get_markeredgewidth(), group) pts = _scaled(xyz, ax) if line._axlim_clip: pts[_outside_limits(xyz, ax)] = np.nan for i in _marked(line.get_markevery(), len(pts)): if not np.isnan(pts[i]).any(): items.append((_POINT, [pts[i:i + 1]], style)) def _scatter_colours(col): """Face and edge colours in the order the points were given, with mplot3d's shading for depth.""" old = col._z_markers_idx col._z_markers_idx = slice(None) try: return col.get_facecolor(), col.get_edgecolor() finally: col._z_markers_idx = old def _gather_scatter(items, ax, col, group): arrays = [np.ma.filled(np.ma.asanyarray(c, dtype=float), np.nan).ravel() for c in col._offsets3d] n = max((len(a) for a in arrays), default=0) if n == 0: return xyz = np.column_stack([np.broadcast_to(a, n) for a in arrays]) pts = _scaled(xyz, ax) if col._axlim_clip: pts[_outside_limits(xyz, ax)] = np.nan col.update_scalarmappable() sizes = np.atleast_1d(col._sizes3d) widths = np.atleast_1d(col._linewidths3d) paths = col.get_paths() face, edge = _scatter_colours(col) for i in range(n): if np.isnan(pts[i]).any() or len(sizes) == 0: continue f = tuple(_pick(face, i)) if len(face) else (0, 0, 0, 0) e = tuple(_pick(edge, i)) if len(edge) else (0, 0, 0, 0) w = float(_pick(widths, i)) if len(widths) else 0.0 style = _marker_style(_pick(paths, i), float(np.sqrt(_pick(sizes, i))), f, e, w, group) if col.get_depthshade(): style.source = (col, i) # its colour changes as the view turns items.append((_POINT, [pts[i:i + 1]], style)) def _gather(ax, artists): items, handled = [], [] for group, a in enumerate(artists): if not a.get_visible(): continue if a.get_animated(): continue # blitting draws these itself, one at a time; they stay Matplotlib's job if isinstance(a, art3d.Line3D) and a.get_drawstyle() != "default": warnings.warn("rightorder: a line with a step drawstyle is left to Matplotlib and may be drawn out " "of order", stacklevel=2) continue if isinstance(a, art3d.Collection) and a.get_hatch(): warnings.warn("rightorder: hatching is not drawn", stacklevel=2) if isinstance(a, art3d.Poly3DCollection): _gather_polys(items, ax, a, group) elif isinstance(a, art3d.Line3DCollection): _gather_line_collection(items, ax, a, group) elif isinstance(a, art3d.Line3D): _gather_line3d(items, ax, a, group) elif isinstance(a, art3d.Path3DCollection): _gather_scatter(items, ax, a, group) elif isinstance(a, art3d.Collection3D) and hasattr(a, "_3dverts_codes"): _gather_contour_set(items, ax, a, group) else: if isinstance(a, (art3d.Patch3D, art3d.Patch3DCollection)): warnings.warn(f"rightorder: {type(a).__name__} is left to Matplotlib and may be drawn out of " "order", stacklevel=2) continue handled.append(a) return items, handled # ------------------------------------------------------------------ the space partition class _Node: __slots__ = ("normal", "d", "here", "front", "back", "leaf") def __init__(self): self.normal = None self.d = 0.0 self.here = [] self.front = self.back = None self.leaf = None class _Tree: """Binary space partition. It does not depend on the view, so turning the plot reuses it.""" def __init__(self, items, eps): self.eps = eps self.verts = [] # per piece: list of rings, each (k, 3) self.styles = [] self.kinds = [] self.planes = [] # (unit normal, offset) for polygons, else None rng = np.random.default_rng(12345) root_ids = [] for kind, rings, style in items: plane = None if kind == _POLY: plane = self._plane(rings) if plane is None: continue root_ids.append(self._new(kind, rings, style, plane)) self.root = _Node() stack = [(self.root, root_ids)] while stack: node, ids = stack.pop() self._split_node(node, ids, rng, stack) if len(self.verts) > _MAX_PIECES: raise RuntimeError("rightorder: the scene needs too many pieces; plot with fewer faces " "(for example plot_surface(..., rcount=40, ccount=40))") self._finish() def _new(self, kind, rings, style, plane): self.kinds.append(kind) self.verts.append(rings) self.styles.append(style) self.planes.append(plane) return len(self.verts) - 1 @staticmethod def _plane(rings): pts = np.vstack(rings) normal = sum(_newell(r) for r in rings) length = np.sqrt(normal @ normal) if not length > 1e-12: ring = max(rings, key=len) normal = _newell(ring) length = np.sqrt(normal @ normal) if not length > 1e-12: # A ring whose edges cross can enclose areas that cancel (a bow tie): fit a plane instead. _, spread, axes = np.linalg.svd(pts - pts.mean(axis=0), full_matrices=False) if len(spread) < 3 or not spread[1] > 1e-9: return None # all corners on one line: nothing to fill normal, length = axes[2], 1.0 normal = normal / length return normal, float(normal @ pts.mean(axis=0)) def _split_node(self, node, ids, rng, stack): polys = [i for i in ids if self.kinds[i] == _POLY] if not polys: node.leaf = ids return flat = [np.vstack(self.verts[i]) if len(self.verts[i]) > 1 else self.verts[i][0] for i in ids] lengths = np.fromiter((len(f) for f in flat), int, len(flat)) starts = np.concatenate([[0], np.cumsum(lengths)[:-1]]) pool = np.concatenate(flat) k = min(len(polys), 6) cand = polys if k == len(polys) else [polys[j] for j in rng.choice(len(polys), k, replace=False)] if len(cand) > 1: if len(pool) > 600: sample_starts_idx = np.sort(rng.choice(len(ids), min(len(ids), 160), replace=False)) sample = np.concatenate([flat[j] for j in sample_starts_idx]) s_len = lengths[sample_starts_idx] s_start = np.concatenate([[0], np.cumsum(s_len)[:-1]]) else: sample, s_start = pool, starts normals = np.array([self.planes[i][0] for i in cand]) offs = np.array([self.planes[i][1] for i in cand]) dist = sample @ normals.T - offs hi = np.maximum.reduceat(dist, s_start, axis=0) > self.eps lo = np.minimum.reduceat(dist, s_start, axis=0) < -self.eps cost = 5 * (hi & lo).sum(0) + np.abs((hi & ~lo).sum(0) - (lo & ~hi).sum(0)) chosen = cand[int(np.argmin(cost))] else: chosen = cand[0] normal, off = self.planes[chosen] node.normal, node.d = normal, off dist = pool @ normal - off hi = np.maximum.reduceat(dist, starts) > self.eps lo = np.minimum.reduceat(dist, starts) < -self.eps front, back = [], [] for pos, i in enumerate(ids): if i == chosen or (not hi[pos] and not lo[pos]): node.here.append(i) elif hi[pos] and not lo[pos]: front.append(i) elif lo[pos] and not hi[pos]: back.append(i) else: a, b = self._cut(i, normal, off) if a is not None: front.append(a) if b is not None: back.append(b) if front: node.front = _Node() stack.append((node.front, front)) if back: node.back = _Node() stack.append((node.back, back)) def _cut(self, i, normal, off): kind, rings, style, plane = self.kinds[i], self.verts[i], self.styles[i], self.planes[i] sides = ([], []) if kind == _LINE: a, b = rings[0] da, db = a @ normal - off, b @ normal - off m = a + (b - a) * (da / (da - db)) first = np.array([a, m]) second = np.array([m, b]) if da > 0: sides[0].append(first) sides[1].append(second) else: sides[1].append(first) sides[0].append(second) else: for r in rings: d = r @ normal - off nxt = np.roll(r, -1, axis=0) dn = np.roll(d, -1) crossing = ((d > self.eps) & (dn < -self.eps)) | ((d < -self.eps) & (dn > self.eps)) with np.errstate(all="ignore"): t = np.where(crossing, d / (d - dn), 0.0) cut = r + (nxt - r) * t[:, None] both = np.empty((2 * len(r), 3)) both[0::2], both[1::2] = r, cut for s, keep_vertex in enumerate((d >= -self.eps, d <= self.eps)): mask = np.empty(2 * len(r), bool) mask[0::2], mask[1::2] = keep_vertex, crossing part = both[mask] if len(part) >= 3: sides[s].append(part) out = [] for s in sides: out.append(self._new(kind, s, style, plane) if s else None) return out def _finish(self): """Flatten the vertices of the pieces that ended up in the tree, so a view projects them at once.""" used = [] stack = [self.root] while stack: node = stack.pop() used.extend(node.leaf if node.leaf is not None else node.here) stack.extend(c for c in (node.front, node.back) if c is not None) self.slot = {} chunks, ring_lengths, spans = [], [], [] total = 0 for i in used: first_ring = len(ring_lengths) begin = total for r in self.verts[i]: chunks.append(r) ring_lengths.append(len(r)) total += len(r) self.slot[i] = len(spans) spans.append((begin, total, first_ring, len(ring_lengths))) self.used = used self.pool = np.concatenate(chunks) if chunks else np.zeros((0, 3)) self.ring_lengths = ring_lengths self.spans = spans def order(self, eye, direction, depth): """Piece numbers from farthest to nearest. `eye` is the viewpoint, or None with a view `direction`.""" out = [] stack = [(self.root, False)] while stack: node, ready = stack.pop() if ready: here = node.here if len(here) > 1: # Same plane: faces first, then the lines and points lying on them. here = sorted(here, key=lambda i: (self.kinds[i] != _POLY, self.styles[i].group, i)) out.extend(here) continue if node.leaf is not None: out.extend(sorted(node.leaf, key=lambda i: -depth[self.slot[i]])) continue side = (node.normal @ eye - node.d) if eye is not None else node.normal @ direction near, far = (node.front, node.back) if side > 0 else (node.back, node.front) # Last pushed is handled first: far side, then this plane, then the near side. if near is not None: stack.append((near, False)) stack.append((node, True)) if far is not None: stack.append((far, False)) return out # ------------------------------------------------------------------ lines and points def _first_occluder(samples, sample_rank, polys, poly_rank, planes, tol): """For each sample (x px, y px, depth), the paint rank of the first later face that hides it. `polys` is a list of lists of (k, 3) rings in (x px, y px, depth); `planes` gives each face's depth as a * x + b * y + c, with NaN for a face seen edge on. """ result = np.full(len(samples), np.inf) if not len(samples) or not polys: return result boxes = np.empty((len(polys), 4)) slack = np.zeros(len(polys)) # how far each face's own corners lie from its plane, in depth edge_a, edge_b, edge_count, edge_start = [], [], np.zeros(len(polys), int), np.zeros(len(polys), int) total = 0 for n, rings in enumerate(polys): pts = rings[0] if len(rings) == 1 else np.concatenate(rings) boxes[n] = (*pts[:, :2].min(0), *pts[:, :2].max(0)) if np.isfinite(planes[n, 0]): off = pts[:, 2] - (planes[n, 0] * pts[:, 0] + planes[n, 1] * pts[:, 1] + planes[n, 2]) slack[n] = np.abs(off).max() edge_start[n] = total for r in rings: edge_a.append(r[:, :2]) edge_b.append(np.roll(r[:, :2], -1, axis=0)) total += len(r) edge_count[n] = total - edge_start[n] edge_a = np.concatenate(edge_a) edge_b = np.concatenate(edge_b) # a grid over the screen pairs each sample with the faces whose box could cover it lo = boxes[:, :2].min(0) hi = boxes[:, 2:].max(0) cell = max(float(np.median(np.maximum(boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]))), 4.0) cell = max(cell, float((hi - lo).max()) / 400) size = np.floor((hi - lo) / cell).astype(int) + 1 grid = {} ranges = np.floor((boxes - np.tile(lo, 2)) / cell).astype(int) for n in np.nonzero(~np.isnan(planes[:, 0]))[0]: x0, y0, x1, y1 = ranges[n] for gx in range(x0, x1 + 1): for gy in range(y0, y1 + 1): grid.setdefault(gx * size[1] + gy, []).append(n) cells = np.floor((samples[:, :2] - lo) / cell).astype(int) inside_grid = ((cells >= 0) & (cells < size)).all(1) keys = np.where(inside_grid, cells[:, 0] * size[1] + cells[:, 1], -1) order = np.argsort(keys, kind="stable") uniq, begin = np.unique(keys[order], return_index=True) ends = np.append(begin[1:], len(order)) pair_s, pair_p, pending = [], [], 0 def flush(): nonlocal pending if not pair_s: return s = np.concatenate(pair_s) p = np.concatenate(pair_p) pair_s.clear() pair_p.clear() pending = 0 xy = samples[s, :2] keep = ((poly_rank[p] > sample_rank[s]) & (xy[:, 0] >= boxes[p, 0]) & (xy[:, 0] <= boxes[p, 2]) & (xy[:, 1] >= boxes[p, 1]) & (xy[:, 1] <= boxes[p, 3])) s, p = s[keep], p[keep] face_depth = planes[p, 0] * samples[s, 0] + planes[p, 1] * samples[s, 1] + planes[p, 2] keep = face_depth < samples[s, 2] - tol - slack[p] # smaller depth is nearer s, p = s[keep], p[keep] if not len(s): return counts = edge_count[p] offsets = np.concatenate([[0], np.cumsum(counts)[:-1]]) e = np.arange(counts.sum()) - np.repeat(offsets, counts) + np.repeat(edge_start[p], counts) owner = np.repeat(np.arange(len(s)), counts) ax_, ay = edge_a[e, 0], edge_a[e, 1] bx, by = edge_b[e, 0], edge_b[e, 1] px, py = samples[s[owner], 0], samples[s[owner], 1] with np.errstate(all="ignore"): hit = ((ay > py) != (by > py)) & (px < ax_ + (py - ay) / (by - ay) * (bx - ax_)) covered = np.add.reduceat(hit.astype(int), offsets) % 2 == 1 np.minimum.at(result, s[covered], poly_rank[p[covered]]) for key, a, b in zip(uniq, begin, ends): faces = grid.get(int(key)) if key < 0 or not faces: continue faces = np.array(faces) members = order[a:b] pair_s.append(np.repeat(members, len(faces))) pair_p.append(np.tile(faces, len(members))) pending += len(members) * len(faces) if pending > 1_000_000: flush() flush() return result def _screen_planes(ax, m, tree_planes): """Each face plane as depth = a * x + b * y + c in screen pixels, worked out exactly from the 3D plane.""" if not tree_planes: return np.zeros((0, 3)) flat = np.array([[*normal, -off] for normal, off in tree_planes]) clip = flat @ np.linalg.inv(m) # the same planes in the camera's (x, y, z, w) # pixels come from x/w and y/w by a shift and a stretch origin, ones = ax.transData.transform([[0.0, 0.0], [1.0, 1.0]]) stretch = ones - origin with np.errstate(all="ignore"): a = -clip[:, 0] / clip[:, 2] b = -clip[:, 1] / clip[:, 2] c = -clip[:, 3] / clip[:, 2] edge_on = np.abs(clip[:, 2]) <= 1e-9 * np.linalg.norm(clip, axis=1) out = np.column_stack([a / stretch[0], b / stretch[1], c - a * origin[0] / stretch[0] - b * origin[1] / stretch[1]]) out[edge_on] = np.nan return out # ------------------------------------------------------------------ joining see-through pieces def _overlaps(outlines, margins, wanted=None): """For each outline, the earlier outlines whose interiors overlap it on screen. Shapes that only touch along an edge do not count. Outlines are treated as convex, which can only report extra overlaps.""" n = len(outlines) boxes = np.array([(*o.min(0), *o.max(0)) for o in outlines]) boxes[:, :2] -= margins[:, None] boxes[:, 2:] += margins[:, None] low = boxes[:, :2].min(0) extent = np.maximum(boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]) cell = max(float(np.median(extent)), 4.0, float((boxes[:, 2:].max(0) - low).max()) / 400) ranges = np.floor((boxes - np.tile(low, 2)) / cell).astype(int) grid = {} for i, (x0, y0, x1, y1) in enumerate(ranges): for gx in range(x0, x1 + 1): for gy in range(y0, y1 + 1): grid.setdefault((gx, gy), []).append(i) first, second = [], [] for members in grid.values(): if len(members) < 2: continue m = np.array(members) b = boxes[m] hit = ((b[:, None, 0] < b[None, :, 2]) & (b[None, :, 0] < b[:, None, 2]) & (b[:, None, 1] < b[None, :, 3]) & (b[None, :, 1] < b[:, None, 3])) i, j = np.nonzero(np.triu(hit, 1)) first.append(m[i]) second.append(m[j]) earlier = [[] for _ in range(n)] if not first: return earlier pairs = np.unique(np.concatenate(first) * n + np.concatenate(second)) a, b = pairs // n, pairs % n if wanted is not None: a, b = a[wanted[b]], b[wanted[b]] most = max(len(o) for o in outlines) padded = np.array([np.concatenate([o, np.repeat(o[-1:], most - len(o), 0)]) for o in outlines]) px, py = padded[..., 0], padded[..., 1] # Separating axis test, one edge at a time, dropping each pair as soon as an edge separates it. # A pair with a stroke (a margin) is kept whenever the widened boxes meet. solid = (margins[a] + margins[b]) > 0 kept_a, kept_b = a[solid], b[solid] a, b = a[~solid], b[~solid] lengths = np.array([len(o) for o in outlines]) for second_shape in (False, True): for k in range(most): if not len(a): break own = b if second_shape else a following = np.where(k + 1 < lengths[own], k + 1, 0) usable = k < lengths[own] ax_ = py[own, k] - py[own, following] ay = px[own, following] - px[own, k] norm = np.hypot(ax_, ay) usable &= norm > 1e-9 norm = np.where(usable, norm, 1.0) ua = (px[a] * ax_[:, None] + py[a] * ay[:, None]) ub = (px[b] * ax_[:, None] + py[b] * ay[:, None]) depth = np.minimum(ua.max(1) - ub.min(1), ub.max(1) - ua.min(1)) / norm stays = ~(usable & (depth <= 0.02)) a, b = a[stays], b[stays] for i, j in zip(np.concatenate([a, kept_a]), np.concatenate([b, kept_b])): earlier[j].append(i) return earlier def _join_see_through(paths, faces, edges, widths, dashes, aas, is_fill, pt): """Fill neighbouring see-through pieces of one colour as a single shape. Painted one by one, see-through pieces leave a mesh of seams: pale cracks with smoothing on, doubled colour with it off. One compound shape has neither. A piece may join an earlier shape of its colour only if it overlaps nothing painted from that shape onwards, so the order that matters is unchanged. """ n = len(paths) clear = [is_fill[i] and faces[i][3] < 0.999 for i in range(n)] if sum(clear) < 2: return paths, faces, edges, widths, dashes, aas outlines, margins = [], np.zeros(n) for i, path in enumerate(paths): v = path.vertices if is_fill[i]: outlines.append(v[:-1]) else: # a line or marker: take its box, widened by its stroke (x0, y0), (x1, y1) = v.min(0), v.max(0) outlines.append(np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])) margins[i] = widths[i] * pt / 2 + 0.5 earlier = _overlaps(outlines, margins, np.array(clear)) groups = [] # lists of piece numbers, in painting order by_colour = {} group_of = [0] * n for i in range(n): target = None if clear[i] and not (paths[i].codes == Path.MOVETO).sum() > 1: after = max((group_of[j] for j in earlier[i]), default=-1) key = (tuple(np.round(np.array(faces[i][:3]) * 80).astype(int)), round(faces[i][3], 3)) open_groups = by_colour.setdefault(key, []) k = int(np.searchsorted(open_groups, after, side="right")) if k < len(open_groups): target = open_groups[k] if target is None: target = len(groups) groups.append([i]) if clear[i] and not (paths[i].codes == Path.MOVETO).sum() > 1: open_groups.append(target) else: groups[target].append(i) group_of[i] = target out = ([], [], [], [], [], []) for members in groups: head = members[0] if len(members) == 1: path = paths[head] smooth = True if clear[head] else aas[head] else: verts, codes = [], [] for i in members: v = paths[i].vertices[:-1] area = np.dot(v[:, 0], np.roll(v[:, 1], -1)) - np.dot(v[:, 1], np.roll(v[:, 0], -1)) if area < 0: # every ring the same way round, so they add up v = v[::-1] ring = np.vstack([v, v[:1]]) c = np.full(len(ring), Path.LINETO, Path.code_type) c[0], c[-1] = Path.MOVETO, Path.CLOSEPOLY verts.append(ring) codes.append(c) path = Path(np.concatenate(verts), np.concatenate(codes)) smooth = True for store, value in zip(out, (path, faces[head], edges[head], widths[head], dashes[head], smooth)): store.append(value) return out # ------------------------------------------------------------------ the artist that paints the result class _Scene(PathCollection): def __init__(self, ax): super().__init__([], transform=IdentityTransform()) self._owner = ax self._tree = None self._signature = None self._handled = [] self._hidden = {} self.stats = {} self.set_gid("rightorder") self.set_label("_rightorder") self.set_picker(None) # mplot3d calls this on every collection before drawing any of them def do_3d_projection(self): return np.inf # sorted to the bottom of the data layers: text and legends stay above def _restore(self): for artist in self._hidden.values(): artist.__dict__.pop("draw", None) self._hidden = {} def _sync(self): """Rebuild the partition if the plotted data or styles changed, and silence the originals.""" ax = self._owner artists = [a for a in ax._children if a is not self] sig = _signature(ax, artists) if sig != self._signature: items, self._handled = _gather(ax, artists) if items: pts = np.concatenate([r for _, rings, _ in items for r in rings]) low, high = pts.min(0), pts.max(0) span = np.where(high - low > 0, high - low, 1.0) # Each direction is scaled on its own, which keeps planes flat and tolerances meaningful. self._centre, self._span = (low + high) / 2, span local = [(k, [(r - self._centre) / span for r in rings], st) for k, rings, st in items] see_through = any(st.kind == _POLY and st.face[3] < 0.999 for _, _, st in local) eps, flat_to = _CLEAR if see_through else _SOLID self._tree = _Tree(_flatten(local, flat_to), eps) else: self._tree = None self._signature = sig handled = self._handled wanted = {id(a): a for a in handled} for key, artist in list(self._hidden.items()): if key not in wanted: artist.__dict__.pop("draw", None) del self._hidden[key] for key, artist in wanted.items(): if key not in self._hidden: artist.draw = _Silenced(artist) self._hidden[key] = artist def draw(self, renderer): if not self.get_visible(): return self._sync() if self._tree is None or not self._tree.used: return self._paint(renderer) super().draw(renderer) self.stale = False def _paint(self, renderer): ax, tree = self._owner, self._tree # the camera, expressed in the tree's coordinates place = np.eye(4) place[:3, :3] = np.diag(self._span) place[:3, 3] = self._centre m = ax.M @ place h = tree.pool @ m[:, :3].T + m[:, 3] w = h[:, 3] screen = np.empty((len(h), 3)) screen[:, :2] = ax.transData.transform(h[:, :2] / w[:, None]) screen[:, 2] = h[:, 2] / w _, _, vt = np.linalg.svd(m[[0, 1, 3]]) null = vt[-1] # the point that projects nowhere: the viewpoint eye = direction = None if abs(null[3]) > 1e-9 * np.abs(null).max(): eye = null[:3] / null[3] else: # parallel projection: head towards smaller depth w_sign = np.sign(m[3, 3] + m[3, :3] @ tree.pool[0]) if (m[2] @ null) * w_sign > 0: null = -null direction = null[:3] spans = tree.spans starts = np.array([s[0] for s in spans]) counts = np.array([s[1] - s[0] for s in spans]) depth = np.add.reduceat(screen[:, 2], starts) / counts order = tree.order(eye, direction, depth) pt = renderer.points_to_pixels(1.0) scale = max(np.ptp(screen[:, 2]), 1e-12) tol = 2e-6 * scale def rings_of(i): _, _, a, b = spans[tree.slot[i]] at = spans[tree.slot[i]][0] out = [] for length in tree.ring_lengths[a:b]: out.append(screen[at:at + length]) at += length return out polys, poly_rank, solid, others = [], [], [], [] for rank, i in enumerate(order): if tree.kinds[i] == _POLY: polys.append(rings_of(i)) poly_rank.append(rank) solid.append(tree.styles[i].face[3] >= 0.999) else: others.append((rank, i)) poly_rank = np.array(poly_rank, float) planes = _screen_planes(ax, m, [tree.planes[order[int(r)]] for r in poly_rank]) solid = np.array(solid, bool) samples, sample_rank, parts = [], [], [] for rank, i in others: begin, end, _, _ = spans[tree.slot[i]] if tree.kinds[i] == _POINT: samples.append(screen[begin:end]) sample_rank.append([rank]) parts.append((rank, i, screen[begin:end], 1)) else: a, b = screen[begin], screen[begin + 1] n = max(1, int(np.ceil(np.hypot(*(b[:2] - a[:2])) / _STEP_PX))) cut = a + (b - a) * np.linspace(0, 1, n + 1)[:, None] samples.append((cut[:-1] + cut[1:]) / 2) sample_rank.append([rank] * n) parts.append((rank, i, cut, n)) if samples: samples = np.concatenate(samples) sample_rank = np.concatenate(sample_rank).astype(float) kinds_of_samples = np.concatenate([np.full(max(n, 1) if tree.kinds[i] == _LINE else 1, tree.kinds[i]) for _, i, _, n in parts]) def occluder(which, own_rank): return _first_occluder(samples, own_rank, [polys[k] for k in np.nonzero(which)[0]], poly_rank[which], planes[which], tol) # Whether a solid face hides a sample is a question of geometry alone, so every solid face is # asked, wherever the partition put it. See-through faces matter only if painted afterwards. behind_solid = occluder(solid, np.full(len(samples), -1.0)) behind_clear = occluder(~solid, sample_rank) # Hidden by a solid face: not painted (a dot is still painted where the partition put it, so # that its edge can show past the face's edge). Otherwise move it later: to just before the first # see-through face that covers it, or to the very end, so that a face beside it cannot paint over # half of its width. slots = np.where(np.isfinite(behind_solid), np.where(kinds_of_samples == _POINT, sample_rank, -1.0), np.where(np.isfinite(behind_clear), behind_clear - 0.5, float(len(order)))) else: slots = np.zeros(0) # Where each piece goes in the painting sequence. A line or point is moved later, to just before the # first face that really hides it, so that a neighbouring face cannot paint over half of its width. entries = [] # (slot, tie_break, tie_break2, kind, data, style, source) for rank, i in enumerate(order): if tree.kinds[i] == _POLY: entries.append((rank, (0.0, 0), rank, _POLY, i, tree.styles[i], i)) at = 0 for rank, i, cut, n in parts: found = slots[at:at + n] at += n style = tree.styles[i] run = 0 for j in range(1, n + 1): if j == n or found[j] != found[run]: slot = found[run] if slot < 0: run = j continue dot = tree.kinds[i] == _POINT data = cut[0] if dot else cut[run:j + 1] depth_here = cut[0, 2] if dot else data[:, 2].mean() if slot == len(order): # Far to near. Lines at the same depth (one drawn over another) go in plotting order, # not in whatever order rounding errors would give them piece by piece. tie = (-np.round(depth_here / (2e-3 * scale)), style.group) else: tie = (-depth_here if dot else 0.0, 0) entries.append((slot, tie, rank, tree.kinds[i], data, style, i)) run = j entries.sort(key=lambda e: (e[0], e[1], e[2])) paths, faces, edges, widths, dashes, aas = [], [], [], [], [], [] is_fill = [] blank = (0, 0, 0, 0) chain = None # [list of arrays, style] of line pieces that join end to end def end_chain(): nonlocal chain if chain is not None: xy = np.concatenate([chain[0][0]] + [c[1:] for c in chain[0][1:]]) st = chain[1] paths.append(Path(xy)) faces.append(blank) edges.append(st.edge) widths.append(st.width) dashes.append(st.dash) aas.append(st.aa) is_fill.append(False) chain = None dash_used = False shaded = {} for slot, _, _, kind, data, style, source in entries: if kind == _LINE: xy = data[:, :2] if chain is not None and chain[1] is style: last = chain[0][-1][-1] if np.abs(last - xy[0]).max() < 1e-6: chain[0].append(xy) continue if np.abs(last - xy[-1]).max() < 1e-6: chain[0].append(xy[::-1]) continue end_chain() chain = [[xy], style] dash_used = dash_used or style.dash[1] is not None continue end_chain() if kind == _POLY: rings = rings_of(data) if len(rings) == 1: xy = rings[0][:, :2] xy = np.vstack([xy, xy[:1]]) codes = np.full(len(xy), Path.LINETO, Path.code_type) codes[0], codes[-1] = Path.MOVETO, Path.CLOSEPOLY else: xy, codes = [], [] for r in rings: ring = np.vstack([r[:, :2], r[:1, :2]]) c = np.full(len(ring), Path.LINETO, Path.code_type) c[0], c[-1] = Path.MOVETO, Path.CLOSEPOLY xy.append(ring) codes.append(c) xy, codes = np.concatenate(xy), np.concatenate(codes) paths.append(Path(xy, codes)) faces.append(style.face) opaque = style.face[3] >= 0.999 outlined = opaque and style.seam edges.append(style.face if outlined else blank) widths.append(_SEAM_PT if outlined else 0.0) dashes.append((0, None)) aas.append(True) is_fill.append(True) else: marker = style.marker verts = marker.vertices * (style.size * pt) + data[:2] paths.append(Path(verts, marker.codes)) face_colour, edge_colour = style.face, style.edge if style.source is not None: col, n = style.source if id(col) not in shaded: shaded[id(col)] = _scatter_colours(col) both = shaded[id(col)] face_colour = tuple(_pick(both[0], n)) if len(both[0]) else face_colour edge_colour = tuple(_pick(both[1], n)) if len(both[1]) else edge_colour faces.append(face_colour) edges.append(edge_colour) widths.append(style.width) dashes.append((0, None)) aas.append(True) is_fill.append(False) end_chain() paths, faces, edges, widths, dashes, aas = _join_see_through( paths, faces, edges, widths, dashes, aas, is_fill, pt) self.set_paths(paths) self.set_facecolor(np.array(faces) if faces else "none") self.set_edgecolor(np.array(edges) if edges else "none") self.set_linewidths(widths) self.set_linestyle(dashes if dash_used else "solid") self.set_antialiased(aas) self.set_joinstyle("round") self.set_capstyle("butt" if dash_used else "round") self.stats = {"pieces": len(tree.used), "painted": len(paths)} class _Silenced: """Stands in for an artist's own draw method while the scene paints it. An animated artist still draws itself, because blitting (FuncAnimation with blit=True) asks each one to, outside a full redraw.""" def __init__(self, artist): self.artist = artist def __call__(self, renderer=None, *args, **kwargs): if self.artist.get_animated(): return type(self.artist).draw(self.artist, renderer, *args, **kwargs) return None def _bytes(value): if value is None: return b"" data = np.ma.asanyarray(value) mask = np.ma.getmask(data) raw = np.ascontiguousarray(np.ma.getdata(data)) if raw.dtype == object: return repr(value).encode() return raw.tobytes() + (b"" if mask is np.ma.nomask else np.ascontiguousarray(mask).tobytes()) def _signature(ax, artists): """Changes whenever something that goes into the partition changes. Turning the view does not count.""" parts = [ax.get_xscale(), ax.get_yscale(), ax.get_zscale()] for a in artists: if not a.get_visible() or a.get_animated(): continue clip = getattr(a, "_axlim_clip", False) if clip: parts.append(str((ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()))) if isinstance(a, art3d.Poly3DCollection): if a._A is not None: a.update_scalarmappable() if a._face_is_mapped: a._facecolor3d = a._facecolors if a._edge_is_mapped: a._edgecolor3d = a._edgecolors values = [a._faces, a._invalid_vertices, a._facecolor3d, a._edgecolor3d, a.get_linewidth()] extra = (str(a._linestyles), None if a._codes3d is None else repr(a._codes3d)) elif isinstance(a, art3d.Line3DCollection): values = list(a._segments3d) + [a.get_edgecolor(), a.get_facecolor(), a.get_linewidth()] extra = str(a._linestyles) elif isinstance(a, art3d.Line3D): values = list(a.get_data_3d()) extra = repr((a.get_color(), a.get_alpha(), a.get_linewidth(), a.get_linestyle(), a.get_marker(), a.get_markersize(), a.get_markerfacecolor(), a.get_markeredgecolor(), a.get_markeredgewidth(), a.get_markevery(), a.get_drawstyle())) elif isinstance(a, art3d.Path3DCollection): a.update_scalarmappable() values = list(a._offsets3d) + [a._facecolors, a._edgecolors, a._sizes3d, a._linewidths3d, a._alpha] + [p.vertices for p in a.get_paths()] extra = repr((a.get_depthshade(), str(a._edgecolors) if isinstance(a._edgecolors, str) else "")) elif isinstance(a, art3d.Collection3D) and hasattr(a, "_3dverts_codes"): a.update_scalarmappable() values = [v for v, _ in a._3dverts_codes] + [c for _, c in a._3dverts_codes] + [ a.get_facecolor(), a.get_edgecolor(), a.get_linewidth()] extra = str(a._linestyles) else: parts.append((id(a), type(a).__name__)) continue parts.append((id(a), extra, hash(b"|".join(_bytes(v) for v in values)))) return hash(tuple(parts)) def _fix_axes(ax): old = getattr(ax, "_rightorder_scene", None) if old is not None: if old in ax.get_children(): return old old._restore() # the axes were cleared since scene = _Scene(ax) # add_artist, not add_collection: the latter would convert this into a 3D collection and move the limits. ax.add_artist(scene) ax._rightorder_scene = scene return scene def fix(target=None): """Draw a 3D axes, or every 3D axes in a figure, in the right order. With no argument: the current figure. Call it any time; things plotted afterwards are included too. Returns `target`. """ if target is None: import matplotlib.pyplot as plt target = plt.gcf() if isinstance(target, axes3d.Axes3D): _fix_axes(target) return target axes = [a for a in getattr(target, "axes", []) if isinstance(a, axes3d.Axes3D)] if not axes: warnings.warn("rightorder.fix: found no 3D axes", stacklevel=2) for a in axes: _fix_axes(a) return target def unfix(target=None): """Go back to Matplotlib's own drawing.""" if target is None: import matplotlib.pyplot as plt target = plt.gcf() axes = [target] if isinstance(target, axes3d.Axes3D) else list(getattr(target, "axes", [])) for ax in axes: scene = getattr(ax, "_rightorder_scene", None) if scene is not None: scene._restore() if scene in ax.get_children(): scene.remove() ax._rightorder_scene = None return target