Rotate a Matplotlib 3D Scatter Plot
This guide shows you how to rotate a 3D scatter plot in Matplotlib, giving you full control over the viewing angle to better explore your data. You’ll learn the interactive method (click-and-drag) and the programmatic approach (setting the elevation and azimuth angles), which is essential for creating a specific viewpoint for a static image or animation.
What You’ll Need
- Python installed (3.6 or later recommended).
- Matplotlib installed (
pip install matplotlib). - A basic understanding of Python and Matplotlib’s
pyplotinterface.
Step-by-Step
- Import the necessary libraries.
Start by importingmatplotlib.pyplotfor plotting andmpl_toolkits.mplot3dfor 3D axes. The latter is automatically loaded when you create a 3D projection, but it’s good practice to import it explicitly.import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D - Create your data.
Generate or load the data you want to plot. For a simple example, create three arrays for x, y, and z coordinates.import numpy as np x = np.random.rand(50) y = np.random.rand(50) z = np.random.rand(50) - Create a figure and a 3D axis.
Useplt.subplots()withprojection='3d'to get a 3D axes object.fig, ax = plt.subplots(subplot_kw={'projection': '3d'}) - Plot the scatter points.
Use thescatter()method on the axes, passing your x, y, and z data.ax.scatter(x, y, z) - Display the plot.
Callplt.show()to display the plot in a window.plt.show() - Rotate interactively (manual).
Once the plot window appears, click and hold the left mouse button anywhere on the plot, then drag to rotate. The view will update in real time. Release the button to stop rotating. This is the quickest way to explore your data from different angles. - Set the view angle programmatically.
To set a specific viewing angle (e.g., for a reproducible figure), use theview_init()method on the axes object. It takes two parameters:elev(elevation angle in degrees, the angle between the line of sight and the horizontal plane) andazim(azimuth angle in degrees, the rotation around the vertical axis).ax.view_init(elev=30, azim=45) - Update the plot after changing the view.
If you change the view after the plot is displayed, you may need to callplt.draw()to refresh the figure. In most interactive environments, it updates automatically, but it’s safe to add it.plt.draw() - Save the rotated plot.
To save the figure with the chosen rotation, callplt.savefig()after setting the view.ax.view_init(elev=20, azim=120) plt.savefig('rotated_scatter.png', dpi=150)
Common Mistakes
- Forgetting to import
Axes3D. In older versions of Matplotlib, you must importmpl_toolkits.mplot3dexplicitly. In recent versions (3.1+), it’s automatic, but the import doesn’t hurt. - Using
plt.rotate()or similar non-existent functions. There is noplt.rotate(); rotation is done viaax.view_init()or interactively. - Setting the view after
plt.show()in a script. In a non-interactive script,plt.show()blocks execution until the window is closed. Set the view before callingplt.show(). - Confusing elevation and azimuth. Elevation is the vertical angle (up/down), azimuth is the horizontal angle (left/right). Swapping them gives a different orientation.
Tips
- Use
ax.view_init()for consistent figures. For reports or publications, always set the view explicitly so every reader sees the same angle. - Animate the rotation. You can create a smooth rotation by looping over azimuth angles and updating the view in a
FuncAnimation.from matplotlib.animation import FuncAnimation def update(angle): ax.view_init(elev=30, azim=angle) return fig, ani = FuncAnimation(fig, update, frames=range(0, 360, 2), interval=50) plt.show() - Adjust the aspect ratio. Use
ax.set_box_aspect([1,1,1])to make the plot visually uniform in all directions, which helps avoid distortion when rotating. - Use keyboard shortcuts. In the interactive window, you can also use the arrow keys to rotate slightly, and the ‘r’ key to reset the view.
Troubleshooting
- The plot doesn’t rotate when dragging. Ensure you are using the left mouse button. If you’re on a touch device, use one finger to rotate. Also, check that the plot window is active (click on it once).
- The view_init() doesn’t change anything. Make sure you call it on the correct axes object (the one you created with
projection='3d'). Also, ensure you call it beforeplt.show()in a script. - The plot is flat (looks 2D). This usually means the data has very little variation in one dimension. Try scaling the data or using
ax.set_box_aspect([1,1,1])to force a cube-like aspect ratio. - Error: ‘Axes3D’ object has no attribute ‘view_init’ This indicates you’re using a 2D axes. Double-check that you created the axes with
projection='3d'.
Frequently Asked Questions
Q: Can I rotate the plot with the keyboard?
A: Yes, in the interactive window, use the left/right arrow keys to rotate azimuth and up/down to change elevation. Press ‘r’ to reset.
Q: How do I set the rotation to a specific angle for a publication?
A: Use ax.view_init(elev=30, azim=45) (or any angles you prefer) before saving the figure. This makes the rotation reproducible.
Q: Why does my saved image look different from the interactive window?
A: The saved image uses the same view angles, but the size and aspect ratio may differ. Set fig.set_size_inches() and ax.set_box_aspect() to match the interactive window.
Q: Can I rotate the plot automatically in a loop?
A: Yes, use matplotlib.animation.FuncAnimation to update the azimuth angle over frames, creating a rotating effect.
Q: How do I change the rotation of a 3D plot that’s already displayed?
A: In interactive mode, just drag. If you’re in a script, you can’t change it after plt.show() because it blocks; instead, use plt.ion() for interactive mode, or set the view before showing.
Q: What are the default elevation and azimuth angles?
A: The default is elev=30 and azim=-60 (or 300 degrees). You can check by printing ax.elev and ax.azim.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.