Visualizing data involving three variables often requiresthree-dimensional plottingto better understand complex relationships and patterns thattwo-dimensionalplots cannot reveal. Python’s Matplotlib library, through itsmpl_toolkits.mplot3d toolkit, provides powerful support for 3D visualizations. To begin creating 3D plots, the first essential step is to set up a 3D plotting environment by enabling 3D projection on the plot axes.For example:
Pythonimportmatplotlib.pyplotaspltfig=plt.figure()ax=plt.axes(projection='3d')plt.show()
Output
Plotting 3D axes using matplotlibExplanation:
- plt.figure()creates a new figure object, which is a container for all the plot elements.
- fig.add_subplot(111, projection='3d')adds a set of axes to the figure with 3D projection enabled. The 111 means "1 row, 1 column, first subplot".
- plt.show()renders the plot window, displaying the 3D axes.
Example Of Three-dimensional Plotting using Matplotlib
1. 3d Line plot
A3D line plotconnects points in three-dimensional space to visualize a continuous path. It's useful for showing how a variable evolves over time or space in 3D. This example uses sine and cosine functions to draw a spiraling path.
Pythonfrommpl_toolkitsimportmplot3dimportnumpyasnpimportmatplotlib.pyplotaspltfig=plt.figure()ax=plt.axes(projection='3d')z=np.linspace(0,1,100)x=z*np.sin(25*z)y=z*np.cos(25*z)ax.plot3D(x,y,z,'green')ax.set_title('3D Line Plot')plt.show()
Output
3D line plot graph using the matplotlib libraryExplanation:We generate 100 points between 0 and 1 usingnp.linspace()for z, then compute x = z * np.sin(25z) and y = z * np.cos(25z) to form a spiral. The 3D spiral is plotted using ax.plot3D(x, y, z, 'green').
2. 3D Scatter plot
A3D scatter plot displays individual data points in three dimensions, helpful for spotting trends or clusters. Each dot represents a point with (x, y, z) values and color can be used to add a fourth dimension.
Pythonfig=plt.figure()ax=plt.axes(projection='3d')z=np.linspace(0,1,100)x=z*np.sin(25*z)y=z*np.cos(25*z)c=x+y# Color array based on x and yax.scatter(x,y,z,c=c)ax.set_title('3D Scatter Plot')plt.show()
Output
3D point plot using Matplotlib libraryExplanation: Using the samex,y andz values, ax.scatter() plots individual 3D points. Colors are set by c = x + y, adding a fourth dimension to visualize variation across points.
3. Surface Plot
Surface plotsshow a smooth surface that spans across a grid of (x, y) values and is shaped by z values. They’re great for visualizing functions with two variables, providing a clear topography of the data.
Pythonx=np.outer(np.linspace(-2,2,10),np.ones(10))y=x.copy().Tz=np.cos(x**2+y**3)fig=plt.figure()ax=plt.axes(projection='3d')ax.plot_surface(x,y,z,cmap='viridis',edgecolor='green')ax.set_title('Surface Plot')plt.show()
Output
Surface plot using matplotlib libraryExplanation:We create a grid withxandy usingnp.outer() and .T, then computez = np.cos(x**2 + y**3). The surface is visualized withax.plot_surface()usingcmap='viridis' for color andedgecolor='green' for gridlines.
4. Wireframe Plot
Awireframe plotis like a surface plot but only shows the edges or "skeleton" of the surface. It’s useful for understanding the structure of a 3D surface without the distraction of color fill.
Pythondeff(x,y):returnnp.sin(np.sqrt(x**2+y**2))x=np.linspace(-1,5,10)y=np.linspace(-1,5,10)X,Y=np.meshgrid(x,y)Z=f(X,Y)fig=plt.figure()ax=plt.axes(projection='3d')ax.plot_wireframe(X,Y,Z,color='green')ax.set_title('Wireframe Plot')plt.show()
Output
3D wireframe graph using the matplotlib libraryExplanation:We definef(x, y) = sin(√(x² + y²)), generate a meshgrid for x and y, and computezvalues. Usingax.plot_wireframe(), we render the 3D surface as a green wireframe.
5. Contour plot in 3d
This plot combines a 3D surface with contour lines to highlight elevation or depth. It helps visualize the function’s shape and gradient changes more clearly in 3D space.
Pythondeffun(x,y):returnnp.sin(np.sqrt(x**2+y**2))x=np.linspace(-10,10,40)y=np.linspace(-10,10,40)X,Y=np.meshgrid(x,y)Z=fun(X,Y)fig=plt.figure(figsize=(10,8))ax=plt.axes(projection='3d')ax.plot_surface(X,Y,Z,cmap='cool',alpha=0.8)ax.set_title('3D Contour Plot')ax.set_xlabel('x')ax.set_ylabel('y')ax.set_zlabel('z')plt.show()
Output
3D contour plot of a function using matplotlib Explanation:We definefun(x, y) = sin(√(x² + y²)) and generate a dense grid forx and y. The surface is plotted with ax.plot_surface() using alpha=0.8for transparency and axis labels are added for clarity.
6. Surface Triangulation plot
This plot uses triangular meshes to build a 3D surface from scattered or grid data. It's ideal when the surface is irregular or when using non-rectangular grids.
Pythonfrommatplotlib.triimportTriangulationdeff(x,y):returnnp.sin(np.sqrt(x**2+y**2))x=np.linspace(-6,6,30)y=np.linspace(-6,6,30)X,Y=np.meshgrid(x,y)Z=f(X,Y)tri=Triangulation(X.ravel(),Y.ravel())fig=plt.figure(figsize=(10,8))ax=fig.add_subplot(111,projection='3d')ax.plot_trisurf(tri,Z.ravel(),cmap='cool',edgecolor='none',alpha=0.8)ax.set_title('Surface Triangulation Plot')ax.set_xlabel('x')ax.set_ylabel('y')ax.set_zlabel('z')plt.show()
Output
3D contour plot of a function using matplotlib Explanation: After defining the function and generatingx andywithnp.meshgrid(), we flatten them using.ravel() and create a Triangulation object. The surface is plotted with ax.plot_trisurf() using a colormap and transparency.
7. Möbius Strip Plot
AMöbius strip is a one-sided surface with a twist—a famous concept in topology. This plot visualizes its 3D geometry, showing how math and art can blend beautifully.
PythonR=2u=np.linspace(0,2*np.pi,100)v=np.linspace(-1,1,100)u,v=np.meshgrid(u,v)x=(R+v*np.cos(u/2))*np.cos(u)y=(R+v*np.cos(u/2))*np.sin(u)z=v*np.sin(u/2)fig=plt.figure()ax=fig.add_subplot(111,projection='3d')ax.plot_surface(x,y,z,alpha=0.5)ax.set_xlabel('X')ax.set_ylabel('Y')ax.set_zlabel('Z')ax.set_title('Möbius Strip')ax.set_xlim([-3,3])ax.set_ylim([-3,3])ax.set_zlim([-3,3])plt.show()
Output
Mobius strip plot using matplotlib library Explanation:We generate parametersu andv to span the circle and strip width, mesh them and computex,y and z using parametric equations. The twisted strip is plotted with ax.plot_surface() using transparency and custom axis limits.
3D Plotting in Python using Matplotlib