Menu Close

3 Ways to Create Eye-Catching 3D Graphs in Python

Python Programming

Installing Necessary Libraries

Before running the below codes, please make sure you have to install the necessary libraries of python.

Guide to Install Plotting Libraries in Python – Windows/Linux/MacOS

1. Using matplotlib and mplot3d

matplotlib is a popular Python library for creating high-quality visualizations, including 3D plots. mplot3d is a module within matplotlib that provides tools for creating 3D plots. Here’s an example of creating a 3D surface plot using matplotlib and mplot3d:

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Create a 3D grid of points
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Plot the surface
ax.plot_surface(X, Y, Z)

# Set the labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.title('3D Surface Plot')

plt.show()

				
			

This code creates a 3D surface plot of the function z = sin(sqrt(x^2 + y^2)). The plot_surface function is used to create the surface, and the set_xlabel, set_ylabel, and set_zlabel functions are used to label the axes. The resulting plot will be displayed using the show function.

2. Using plotly

plotly is a library that provides interactive data visualization tools, including 3D plots. Here’s an example of creating a 3D surface plot using plotly:

				
					import plotly.graph_objects as go
import numpy as np

# Create a 3D grid of points
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create the plot
fig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y)])

# Set the labels and title
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
                  title='3D Surface Plot')

fig.show()

				
			

3. Using mayavi

mayavi is a Python library for creating 3D scientific visualizations. Here’s an example of creating a 3D surface plot using mayavi:

				
					import numpy as np
from mayavi import mlab

# Create a 3D grid of points
x, y = np.mgrid[-5:5:100j, -5:5:100j]
z = np.sin(np.sqrt(x**2 + y**2))

# Create the plot
mlab.figure(bgcolor=(1,1,1))
surf = mlab.surf(x, y, z)

# Set the labels and title
mlab.xlabel('X')
mlab.ylabel('Y')
mlab.z

				
			

This code creates a 3D surface plot of the function z = sin(sqrt(x^2 + y^2)) using plotly. The Surface function is used to create the surface, and the update_layout function is used to label the axes and set the plot title. The resulting plot will be displayed using the show function.

More Related Stuff