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 |
? Python is a high-level, interpreted programming language regarded for its simplicity and readability. Its syntax emphasizes code readability and lets builders to explicit ideas in fewer strains of code in comparison to languages like C++ or Java. Python helps with multiple programming paradigms, along with...
3 min read
Introduction In the realm of working with data, Python is an excellent tool. With its wide array of libraries and frameworks, Python provides users with a huge collection of tools for working splendidly with data. A widespread activity in programming is the rendition of lists into...
8 min read
Introduction: Python offers a QQ plot, a graphical tool for comparing a dataset's distribution with a known theoretical one, enabling the determination of dataset in following a certain probability distribution. What is a Quantile-Quantile Plot? A quantile-quantile plot (or QQ plot) is a graphical tool used to compare the...
3 min read
The practice of making payments online is becoming increasingly popular as we move closer to modern times. Online payment is particularly advantageous for the customer since it eliminates the issue of free money and saves time. Furthermore, the currency is not necessary for us to...
8 min read
8 Advanced Python Logging Features that You Shouldn't Miss In the world of software development, logging is often an unsung hero. A basic part can have the effect between speedy issue goal and long periods of baffling troubleshooting. While numerous Python engineers are known all about...
6 min read
Introduction Using the os and shutil modules, numerous files in Python may be renamed effectively. Make a list of the file names that need to be renamed first. Afterwards, run the renaming procedure iteratively over the list using functions like os. rename() or shutil.move(). Both the...
4 min read
An Introduction to Python's simple_salesforce Library The simple_salesforce library is a Python package that provides an easy means to communicate with the Salesforce REST API. By abstracting the complexity of API calls, it permits developers to concentrate on writing code rather than managing the raw HTTP requests. Key...
4 min read
PyQt could be a collection of Python ties for the Qt application structure that empowers cross-platform programming with capable graphical user interface(GUIs). One of PyQt's most imperative widgets is the 'QComboBox', a adaptable and for the most part utilized in drop-down list that permit clients...
5 min read
Clean code refers to supply code that isn't simplest practical however additionally clean to study, understand, and maintain. It embodies the ideas of simplicity, readability, and performance. Clean code is like a nicely-organized and nicely-documented piece of literature - it is not simplest approximately attaining a...
22 min read
The minimax algorithm is a decision-making rule in different fields, such as artificial intelligence, decision theory, game theory, statistics, and philosophy. It is designed to minimize the potential loss in the worst-case scenario (maximum loss). The minimax algorithm is a recursive algorithm used to make decisions...
7 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