rightorder: a fix for 3D charts that draw the wrong thing in front

Matplotlib is a widely used chart library for the Python programming language. In its 3D charts, one shape can appear completely on top of another that passes through it, because Matplotlib paints each shape whole, one after another. This Python file cuts the shapes where they cross and paints the pieces from back to front. You add one line to your own plot.

Download rightorder.py

Two plots of hilly terrain with a flat water level. Without the fix the water covers a whole mountain. With the fix the mountains rise out of the water.
A flat water level cutting through hills. Without the fix, one whole hill disappears under the water.

Use it

There is nothing to install beyond Matplotlib itself. Download the file, save it in the same folder as your script, and call rightorder.fix on your 3D plot. A complete example:

import numpy as np
import matplotlib.pyplot as plt
import rightorder

X, Y = np.meshgrid(np.linspace(-2, 2, 60), np.linspace(-2, 2, 60))
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.plot_surface(X, Y, np.sin(X) * np.cos(Y))
ax.plot_surface(X, Y, 0.3 * X)
rightorder.fix(ax)        # or rightorder.fix(fig) for every 3D plot in a figure
plt.show()

It works with surfaces, bars, voxels, filled and line contours, lines, wireframes and scatter points. Saved SVG and PDF files stay vector drawings. rightorder.unfix(ax) undoes it. It was tested only with Matplotlib 3.11.2 on Windows, and it uses internal parts of Matplotlib, so another version may break it. MIT licence.

More examples

A wavy surface, a tilted plane and a spiral line. Without the fix the plane lies on top of everything. With the fix they pass through each other.
A plane and a spiral line passing through a wavy surface.
Two fitted surfaces that cross, drawn without and with the fix.
Two fitted surfaces that cross.
Two cylinders crossing at right angles, drawn without and with the fix.
Two cylinders crossing at right angles.

How it was checked

A separate 3D program, VTK, drew the same shapes from the same viewpoint. The pictures were then compared pixel by pixel, leaving out a thin band along every edge.

Bars cut by a plane: Matplotlib alone, with the fix, and as VTK draws it. The last two match.
Each face has its own test colour, so a face drawn in the wrong order shows up.

Before you rely on it