SoFunction
Updated on 2025-03-03

Python sample code for drawing 3D surface diagrams

Explore the art of drawing 3D surfaces in Python

In the world of data visualization, 3D surface diagrams are a powerful tool that can present complex data patterns in a clear and intuitive way. Python provides a variety of libraries and tools to make creating and customizing 3D surfaces simple and exciting. This article will explain how to draw an impressive 3D surface using Matplotlib and mpl_toolkits.mplot3d libraries in Python.

Preparation

First, make sure that the Matplotlib library is installed in your Python environment. If you haven't installed it, you can use pip to install it:

pip install matplotlib

Import the necessary libraries

Before we start, let's import the necessary libraries first:

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

Create data

Before we draw a 3D surface, we need to create some data. We can use the NumPy library to generate some datasets. Here we take a simple function as an example:

def f(x, y):
    return ((x**2 + y**2))

Create grid points

Next, we need to define the coordinate points we want to display on the surface. We can use functions to generate these points:

x = (-5, 5, 100)
y = (-5, 5, 100)
x, y = (x, y)
z = f(x, y)

Draw 3D surface diagram

Now we are ready to draw our 3D surface. We can use Matplotlib's plot_surface function to implement it:

fig = ()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
()

Customized surface diagram

We can customize our surface diagram with some optional parameters to make it more attractive. For example, we can add contour lines, change color maps, change viewing angles, etc.:

fig = ()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')  # Add contour linesax.view_init(45, 60)  # Change the perspective()

Add tags and titles

When creating 3D surface drawings, it is very important to add labels and titles, which can make the graphics more readable and understandable. We can add axis labels by calling the set_xlabel, set_ylabel and set_zlabel methods, and add titles using the set_title method:

fig = ()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Surface Plot')
()

Add color markers

To understand more clearly the meaning of numerical values ​​in a surface diagram, we can add a color scale. The color scale can show the correspondence between the color and the value. We can use the colorbar method to add color marks:

fig = ()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')
(surf, shrink=0.5, aspect=5)  # Add color markax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Surface Plot with Colorbar')
()

Complete sample code

Here is a complete sample code that includes all customization options:

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

def f(x, y):
    return ((x**2 + y**2))

x = (-5, 5, 100)
y = (-5, 5, 100)
x, y = (x, y)
z = f(x, y)

fig = ()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')
(surf, shrink=0.5, aspect=5)  # Add color markax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Surface Plot with Colorbar')
()

With these customization options, we can create a more informative and aesthetic 3D surface diagram. By mastering these techniques, you will be able to create a variety of 3D visualizations based on your needs.

Add transparency and shadows

In addition to labels, titles, and color marks, we can also enhance the visual effects of 3D surfaces by adjusting transparency and shadow effects. Transparency can make the data distribution in the surface map clearer, while shadows can add a sense of three-dimensionality.

fig = ()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none', alpha=0.7)  # Adjust transparency(surf, shrink=0.5, aspect=5)  
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Surface Plot with Colorbar and Transparency')
()

In addition, we can also add shadow effects by setting the shade parameter to True:

fig = ()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none', shade=True)  # Add shadow(surf, shrink=0.5, aspect=5)  
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Surface Plot with Colorbar and Shadow')
()

Other customization options

In addition to the customization options mentioned above, Matplotlib also provides many other parameters and methods for further customizing 3D surface diagrams, such as modifying the axis range, setting viewing angles, changing color maps, etc. You can choose the appropriate options to customize according to your specific needs.

Further customize color mapping

In 3D surface diagrams, color mapping is an important visual tool that can help us understand the distribution and changes of data more intuitively. In addition to using built-in color mapping, we can also customize color mappings to meet specific needs.

from  import Normalize

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

# Custom color mapnorm = Normalize(vmin=(z), vmax=(z))
colors = (norm(z))

surf = ax.plot_surface(x, y, z, facecolors=colors, shade=False)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('Customized 3D Surface Plot with Color Mapping')
()

Add grid lines

Sometimes, we want to add mesh lines to a 3D surface diagram to help better understand the distribution and shape of the data. We can add grid lines by setting grid parameter to True:

fig = ()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')
(surf, shrink=0.5, aspect=5)  
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Surface Plot with Colorbar and Grid')
(True)  # Add grid lines()

Summarize

This article describes how to create an impressive 3D surface using the Matplotlib library in Python and shows a range of customization options including labels, titles, color markers, transparency, shadows, color maps, and mesh lines. By learning these techniques, we can better demonstrate and understand data, thus providing rich possibilities for data visualization work.

By creating 3D surface diagrams, we can present complex data patterns in an intuitive and clear way, helping us discover patterns and trends in our data. Customization options allow us to adjust the appearance and presentation of the graphics to suit specific needs, thus better meeting our analysis and presentation needs.

All in all, mastering how to create and customize 3D surface diagrams is one of the important skills in the fields of data science and data visualization.

This is the article about the example code of Python drawing 3D surface drawing. For more related content on Python drawing 3D surface drawing, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!