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.
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
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.
Before you rely on it
- Look at your figure. It can be wrong on shapes thinner than a pixel, on surfaces that almost coincide, and where a line passes just behind a fold.
- To hide hairline cracks between pieces, it draws a very thin border on solid pieces, so needle-thin shapes look a little wider.
- It is slower than Matplotlib alone. See-through surfaces are much slower: several seconds for each new view.
- A four-cornered piece of a curved surface is usually slightly bent. There is more than one way to fill a bent piece, so two programs can draw it differently.
- Hatching is not drawn, and the pattern of dashed lines can change. Text and legends stay on top. Flat 2D shapes placed in a 3D plot and lines with a step style are left to Matplotlib, with a warning.
- No person has yet turned a fixed plot with a mouse in a window on screen. It was tested only by having the program imitate the mouse.