3D Surface Plotting in Python Using Matplotlib5 Jan 2025 | 6 min read A 3D surface plot is a graphical representation of a three-dimensional surface in a Cartesian coordinate system. It is a way to visualize a mathematical function or a set of data points in three-dimensional space. In such plots, the x and y axes represent the independent variables, and the z-axis represents the dependent variable. ![]() MatplotlibMatplotlib is a popular plotting library used extensively in Python programming. It provides various tools to create diverse plots, charts, and visualizations. With Matplotlib, you can generate a 3D plot and add a surface plot, colour mapping, labels, a colour bar, and other plot elements. Additionally, Matplotlib offers the plot_surface function for 3D surface plotting and other functions to modify the plot's appearance. In this article, let us explore the different ways of plotting 3D surfaces. Saddle surfaceExampleHere is an example program for plotting 3D surfaces called Saddle Surface. Program Output: ![]() Explanation The program first imports necessary libraries such as numpy, matplotlib.pyplot, and mpl_toolkits.mplot3d for numerical operations, plotting, and 3D plotting capabilities, respectively. The program generates evenly spaced values along the x and y axes using numpy.linspace(), then creates a 2D grid of coordinates using numpy.meshgrid().Next, the z values are computed based on a mathematical function. In this case, z = x**2 - y**2 corresponds to a saddle-shaped surface. The program generates a 3D surface plot using the plot_surface function, where the cmap='viridis' parameter specifies the colour map used for colouring the surface. The program sets labels for the X, Y, and Z axes and adds a title to the plot for better interpretation. Additionally, a colour bar is added to the plot. Finally, the program displays the plot. Sine wave surfaceExampleHere is an example program of a sine wave support surface 3D plot. Program Output: ![]() Explanation In this program, we created a saddle surface. We imported the necessary libraries, such as matplotlib, numpy, and mpl_toolkits. Before creating a plot, we created a 2D grid surface using the linspace() and meshgrid() methods. These methods created a mesh grid-like surface. The z values were computed based on a sine wave function applied to the distance from the origin. The function z = sin(sqrt(x**2 + y**2)) generated a surface that oscillated in the shape of a sine wave. To generate a 3D surface plot, we used the plot_surface function. The parameter cmap='coolwarm' determined the colormap used to color the surface. We set labels for the X, Y, and Z axes and added a title to the plot for better interpretation. Once everything was set up, we displayed the plot. Gaussian surfaceExampleHere is an example program to generate the Gaussian surface plot Program Output: ![]() Explanation This code generates a 3D surface plot of a Gaussian distribution by utilizing the matplotlib library. The numpy module creates a meshgrid of x and y values, then calculates the z values based on a Gaussian function: z = exp(-(x**2 + y**2) / 10). This generates a surface plot that resembles a bell-shaped Gaussian distribution centered at the origin. To create a 3D subplot, the matplotlib.pyplot and mpl_toolkits.mplot3d modules are used, which also includes the Gaussian surface plot, a colorbar with the 'plasma' colormap and labels for the X, Y, and Z axes. The resulting plot provides a clear and visually appealing representation of the Gaussian distribution. Torus surface plotExampleHere is an example program to create a torus surface plot. Program Output: ![]() Explanation This program creates a 3D surface plot that represents a torus using the matplotlib library. The numpy library creates a meshgrid of theta and phi values, which are then used to calculate the torus coordinates in three-dimensional space. The torus is defined by parametric equations for x, y, and z, with parameters R and r determining the major and minor radii, respectively. The resulting surface plot showcases the characteristic donut shape of a torus, where the outer circle represents the major radius R and the smaller, circular cross-section corresponds to the minor radius r. To create a 3D subplot, the matplotlib.pyplot and mpl_toolkits.mplot3d modules are utilized, and the torus surface plot is added. A colorbar is included with the 'magma' colormap, and labels for the X, Y, and Z axes are set. The plot provides a visually appealing representation of a torus in three-dimensional space. 3D surface plotExampleLet us consider an example program for creating a 3D surface plot. Program Output: ![]() Explanation The following Python script has been modified to generate a 3D surface plot using the matplotlib library. This plot showcases a mathematical function defined by the variables X and Y. The script ensures proper computation by correcting the expression for the Z-values, enclosing the terms X**2 and Y**2 within parentheses. The code uses the NumPy library to generate a meshgrid for X and Y within specified ranges. The corrected function Z = X * np.exp(-X**2 - Y**2) defines the height of the surface at each coordinate. The resulting surface plot is rendered using the plot_surface function, with added features such as a colormap ('viridis') for enhanced visualization and edge coloring to delineate surface boundaries. The subplot is formatted with appropriate axis labels and a title to make the plot more easily interpretable. The plot provides a graphical representation of the modified mathematical function in a three-dimensional space, with the colormap aiding in the perception of variations in the function's values. ConclusionIn conclusion, creating a 3D surface plot in Python is a great way to represent three-dimensional data in a visually compelling and insightful manner. With powerful libraries such as Matplotlib and mpl_toolkits.mplot3d, developers can easily create interactive and customizable visualizations. By using NumPy for data manipulation and Matplotlib's sophisticated plotting capabilities, users can transform raw numerical data into dynamic and aesthetically pleasing surfaces that reveal patterns, trends, and relationships within the data. Whether visualizing mathematical functions, scientific simulations, or real-world datasets, crafting 3D surface plots in Python provides a versatile tool for researchers, engineers, and data scientists to gain deeper insights into their data's multidimensional nature. The ability to rotate, zoom, and explore these surfaces enhances the interpretability of complex information, making Python an invaluable platform for creating immersive and informative 3D visualizations. Next TopicAdd-months-to-datetime-object-in-python |
. Introduction: In the world of web development and API interactions, sending HTTP POST requests is a fundamental skill. Python, being a versatile programming language, provides the requests library that simplifies the process of making HTTP requests. In this article, we'll delve into the details of performing...
4 min read
? Python Python is a high-level, interpreted programming language acknowledged for its simplicity and readability. Created by Guido van Rossum and first launched in 1991, Python emphasizes code clarity with its brilliant use of large whitespace. Features Readability: Clear and easy-to-read syntax. Interpreted: Executes code line-through-line. Dynamically Typed: No need to...
3 min read
Competitive programming is a mental sport in which participants must solve specific algorithmic and computational challenges in a predetermined amount of time. Python has grown in popularity among competitive programmers because to its ease of use, readability, and abundance of libraries. Advantages of Using 1. Readability...
4 min read
Convolution is an essential mathematical operation that mixes two functions to produce a third function that represents the quantity of overlap among them. It's frequently utilized in signal processing, photo processing, and system mastering, specifically in deep gaining knowledge of. In the context of sign processing,...
15 min read
? Introduction For robust programming in Python, it is essential to ascertain whether an object possesses a particular attribute. The built-in function hasattr() can be used to determine whether an attribute exists. The object and the attribute name in string form are the two inputs required by...
6 min read
Introduction: In this tutorial we are learning about the tempfile module in Python. The tempfile module in the standard library defines functions for creating temporary files and directories. They are created in a special temporary directory defined by the operating system's file system. Tempfile is a...
6 min read
An Introduction to Sentence Similarity Sentence likeness is a key idea in normal language handling (NLP) that actions how the same two sentences are regarding their importance or content. This estimation is vital for different applications, including: Data recovery Text summarization Question answering systems Plagiarism detection Recommendation systems One famous technique for...
7 min read
? Introduction Pandas is a powerful library in Python used for data manipulation and analysis. Among its many functions, the expanding() method is particularly useful for analyzing data in a rolling or expanding window. In this article, we will delve into the details of how the Series.expanding()...
4 min read
In the ever-evolving landscape of web development, building robust APIs is a crucial skill. Flask, a lightweight and versatile web framework for Python, makes it easy to create APIs that can handle diverse tasks. One fundamental aspect of API development is the ability to return...
7 min read
Python, being a flexible and famous language, gives a sequence of functions and techniques that might be applicable in each branch and discipline. It gives simple syntax and easy-to-understand capabilities, which make Python a flexible language. Using Python, we are able to increase packages for...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India