Save a 3D Scatter Plot in Python using Matplotlib

Recently, I was working on a Python data visualisation project where I needed to create and save a 3D scatter plot for a presentation. The challenge was not just plotting the data in 3D but also saving the figure in a high-quality format that could be reused later.

If you’ve ever tried to save a 3D scatter plot in Python using Matplotlib, you might have noticed that there are multiple ways to do it. In this tutorial, I’ll show you the most practical methods I use to create and save 3D scatter plots in Python.

I’ll also share some tips on how to save your plots as both static images (like PNG, JPG, or PDF) and interactive HTML files that you can open in any web browser.

What is a 3D Scatter Plot in Python?

A 3D scatter plot is a visualisation that shows the relationship between three variables in a three-dimensional space. It’s especially useful when you want to explore data patterns that can’t be seen in 2D plots.

In Python, the Matplotlib library provides an easy way to create 3D plots using the mpl_toolkits.mplot3d module. Once plotted, you can rotate, zoom, and explore the data interactively.

Method 1 – Save 3D Scatter Plot as an Image (PNG, JPG, or PDF)

This is the most common and easy way to save a 3D scatter plot in Python. You can use the savefig() function from Matplotlib to export the plot in any image format you prefer.

Below is a full working example.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Generate random data
np.random.seed(42)
x = np.random.rand(50)
y = np.random.rand(50)
z = np.random.rand(50)

# Create a 3D figure
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

# Plot the 3D scatter
scatter = ax.scatter(x, y, z, c=z, cmap='viridis', s=60)

# Add labels and title
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('3D Scatter Plot Example in Python')

# Add color bar
fig.colorbar(scatter, ax=ax, shrink=0.5, aspect=10)

# Save the figure as a PNG image
plt.savefig('3d_scatter_plot.png', dpi=300, bbox_inches='tight')

# Show the plot
plt.show()

I executed the above example code and added the screenshot below.

Save 3D Scatter Plot in Python Matplotlib

In this example, I generated random data points using NumPy and plotted them in 3D using Matplotlib. The plt.savefig() function saves the plot as a high-resolution PNG image in the current working directory.

You can also change the file extension to .jpg, .pdf, or .svg depending on your needs.
For example:

plt.savefig('3d_scatter_plot.pdf', dpi=300)

Method 2 – Save 3D Scatter Plot as an Interactive HTML File

Sometimes, you may want to interact with your 3D plot, zoom, rotate, or share it online. In such cases, saving it as an interactive HTML file is the best option.

We can achieve this using the Plotly library, which integrates well with Python and Matplotlib.

Here’s how I usually do it:

import plotly.graph_objects as go
import numpy as np

# Generate random data
np.random.seed(10)
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
color = np.random.randint(1, 5, 100)

# Create a 3D scatter plot using Plotly
fig = go.Figure(data=[go.Scatter3d(
    x=x,
    y=y,
    z=z,
    mode='markers',
    marker=dict(
        size=6,
        color=color,
        colorscale='Viridis',
        opacity=0.8
    )
)])

# Add layout details
fig.update_layout(
    title='Interactive 3D Scatter Plot in Python',
    scene=dict(
        xaxis_title='X Axis',
        yaxis_title='Y Axis',
        zaxis_title='Z Axis'
    )
)

# Save the plot as an HTML file
fig.write_html('interactive_3d_scatter.html')

# Display the plot
fig.show()

I executed the above example code and added the screenshot below.

Save 3D Scatter Plot in Matplotlib

This code creates a beautiful, interactive 3D scatter plot that can be rotated and zoomed directly in your browser.
The best part is that you can share the generated interactive_3d_scatter.html file with anyone, no Python environment required.

Method 3 – Save 3D Scatter Plot as a Pickle File (Reusable Python Object)

If you plan to reuse your 3D scatter plot later in your Python project, saving it as a Pickle file is a great idea. This method allows you to save the entire figure object and reload it anytime.

Here’s how you can do it:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pickle

# Generate data
x = np.random.rand(30)
y = np.random.rand(30)
z = np.random.rand(30)

# Create figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='red', marker='o')

ax.set_title('3D Scatter Plot Pickle Example')

# Save figure as pickle file
with open('3d_scatter_plot.pkl', 'wb') as f:
    pickle.dump(fig, f)

# To load the figure later
with open('3d_scatter_plot.pkl', 'rb') as f:
    loaded_fig = pickle.load(f)
    loaded_fig.show()

This approach is handy when you’re working on large Python projects where you need to store and reload visualisations. It keeps all your plot settings, labels, and styles intact.

Method 4 – Save 3D Scatter Plot Automatically After Creation

If you frequently generate multiple 3D scatter plots in Python, automating the saving process can save you time. You can easily integrate the saving logic into your plotting function.

Here’s a quick example:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import os

def save_3d_scatter(x, y, z, filename='auto_3d_plot.png'):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(x, y, z, c=z, cmap='plasma', s=50)
    ax.set_title('Automated 3D Scatter Plot Save')
    plt.savefig(filename, dpi=300, bbox_inches='tight')
    plt.close(fig)
    print(f"Plot saved successfully as {os.path.abspath(filename)}")

# Generate random data
x = np.random.rand(40)
y = np.random.rand(40)
z = np.random.rand(40)

# Save automatically
save_3d_scatter(x, y, z)

I executed the above example code and added the screenshot below.

Save 3D Scatter Plot Matplotlib

This function automatically saves every 3D scatter plot you create, which is very useful when running batch visualisations. You can even modify it to include timestamps in filenames for better version control.

Tips for Saving High-Quality 3D Scatter Plots in Python

Here are a few best practices I follow when saving 3D scatter plots in Python:

  • Increase DPI (dots per inch) for sharper images. Use dpi=300 or higher for print-quality visuals.
  • Use bbox_inches=’tight’ to ensure labels and titles aren’t cut off in the saved image.
  • Choose the right file format — use PNG for reports, SVG for vector graphics, and HTML for interactivity.
  • Add colorbars and legends to make your plots more informative and professional.
  • Set consistent figure sizes using figsize=(width, height) for uniformity across multiple plots.

Common Errors and Fixes

While saving 3D scatter plots in Python, you might encounter a few common issues.
Here are some quick solutions:

  • Error: “Figure size too small”
    Fix: Increase figure size using plt.figure(figsize=(10,8)).
  • Error: “Axes3D object has no attribute ‘savefig’”
    Fix: Always call plt.savefig() on the figure, not the Axes object.
  • Error: “File not found” when saving
    Fix: Ensure the directory exists before saving using os.makedirs() if needed.

Saving a 3D scatter plot in Python is simple once you know the right methods. Whether you want a static image, an interactive HTML file, or a reusable figure, Python’s visualisation ecosystem has you covered.

Personally, I use Matplotlib for static plots and Plotly for interactive ones. Both libraries make it easy to create stunning 3D visualisations that can impress clients or enhance your data reports.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.