Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Saving a 3D-plot in a PDF 3D with Python
To save a 3D plot in a PDF with Python, you can use matplotlib's savefig() method. This approach creates standard 2D PDF files containing the 3D visualization, which is suitable for most documentation and sharing purposes.
Steps
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Add an 'ax' to the figure as part of a subplot arrangement with 3D projection.
Create u, v, x, y and z data points using numpy.
Plot a 3D wireframe or surface.
Set the title and labels of the plot.
Save the current figure using savefig() method with PDF format.
Example − Creating a 3D Wireframe Sphere
Here's how to create a 3D wireframe plot of a sphere and save it to PDF ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure properties
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and 3D axis
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate sphere data
u, v = np.mgrid[0:2 * np.pi:30j, 0:np.pi:20j]
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)
# Plot 3D wireframe
ax.plot_wireframe(x, y, z, color="red")
# Set title and labels
ax.set_title("3D Wireframe Sphere")
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
# Save as PDF
plt.savefig("sphere_3d.pdf", format='pdf', bbox_inches='tight')
# Display plot
plt.show()
The output will display the following 3D wireframe sphere ?
Customizing PDF Output
You can customize the PDF output with additional parameters ?
import matplotlib.pyplot as plt
import numpy as np
# Create a more complex 3D surface
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Generate surface data
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
# Create surface plot
surf = ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.7)
# Add colorbar
fig.colorbar(surf)
# Set labels and title
ax.set_xlabel('X coordinate')
ax.set_ylabel('Y coordinate')
ax.set_zlabel('Z coordinate')
ax.set_title('3D Surface Plot')
# Save with high quality settings
plt.savefig("surface_3d.pdf",
format='pdf',
dpi=300,
bbox_inches='tight',
facecolor='white')
plt.show()
Key Parameters for PDF Saving
| Parameter | Purpose | Example Value |
|---|---|---|
format |
File format | 'pdf' |
dpi |
Resolution quality | 300 |
bbox_inches |
Tight layout | 'tight' |
facecolor |
Background color | 'white' |
Conclusion
Use matplotlib's savefig() method to save 3D plots as PDF files. The bbox_inches='tight' parameter ensures proper layout, while dpi=300 provides high-quality output suitable for printing and professional documentation.
