SoFunction
Updated on 2025-03-03

How to draw various types of 3D graphics using Python and Plotly

Methods to draw 3D graphics through Python and Plotly

In the field of data visualization, 3D graphics are a powerful tool that can demonstrate complex relationships and structures between data. Python has a rich library of data visualization, among which Plotly is a popular tool that provides the function of drawing high-quality three-dimensional graphics. This article will introduce how to use Python and Plotly to draw various types of 3D graphics and give code examples.

Preparation

First, make sure you have the Plotly library installed. You can use the pip command to install:

pip install plotly

Next, we will use Plotly'splotly.graph_objectsModule to create 3D graphics. We will also usenumpyThe library generates some sample data.

import plotly.graph_objects as go
import numpy as np

Draw a scatter plot

First, we will draw a simple scatter plot. Suppose we have some three-dimensional data, which are stored separately inx_datay_dataandz_datamiddle.

# Generate sample data(42)
n_points = 100
x_data = (n_points)
y_data = (n_points)
z_data = (n_points)

# Create a scatter plotfig = (data=[go.Scatter3d(x=x_data, y=y_data, z=z_data, mode='markers')])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
                  title='3D Scatter Plot')
()

The above code will generate a simple three-dimensional scatter plot showing the distribution of randomly generated data points in three-dimensional space.

Draw a surface diagram

Next, we will draw a surface diagram. Suppose we have a functionf(x, y), We want to visualize its surface in three-dimensional space.

# Define functionsdef f(x, y):
    return (x) * (y)

# Generate grid datax_grid = (0, 2*, 50)
y_grid = (0, 2*, 50)
x_grid, y_grid = (x_grid, y_grid)
z_grid = f(x_grid, y_grid)

# Create a surface diagramfig = (data=[(z=z_grid, x=x_grid, y=y_grid)])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
                  title='3D Surface Plot')
()

The above code will generate a three-dimensional surface diagram showing the function surface.

Draw a wireframe

Finally, we will draw a wireframe to show the continuity of the data.

# Generate wireframe datatheta = (-4*, 4*, 100)
z_line = (-2, 2, 100)
x_line = z_line * (theta)
y_line = z_line * (theta)

# Create a wireframefig = (data=[go.Scatter3d(x=x_line, y=y_line, z=z_line, mode='lines')])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
                  title='3D Wireframe Plot')
()

The above code will generate a three-dimensional figure showing the wireframe.

With the above examples, we show how to use Python and Plotly to draw various types of 3D graphics. You can further customize these graphics according to your needs and explore more and more rich features in the Plotly library. Happy drawing!

Draw 3D bar chart

In addition to scatter plots, surface plots and wireframes, we can also draw 3D bar charts to show the differences and relationships between the data.

# Generate sample datacategories = ['A', 'B', 'C', 'D']
values = (1, 10, size=(len(categories), len(categories)))
x_bar, y_bar = ((len(categories)), (len(categories)))
x_bar = x_bar.flatten()
y_bar = y_bar.flatten()
z_bar = np.zeros_like(x_bar)

# Set the height of the bar chartbar_heights = ()

# Create 3D bar chartfig = (data=[go.Bar3d(x=x_bar, y=y_bar, z=z_bar, dx=1, dy=1, dz=bar_heights)])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
                  title='3D Bar Chart')
()

The above code will generate a three-dimensional bar chart showing the relationship between various categories and values.

Custom graphic styles

Plotly offers a wealth of customization options to adjust the style, layout and appearance of the graphics. You can modify the color, line type, label and other attributes of the graph as needed to meet specific visualization needs.

# Customize graphic stylesfig.update_traces(marker=dict(color='rgb(255, 127, 14)', size=10),
                  selector=dict(mode='markers'))
fig.update_layout(scene=dict(xaxis=dict(backgroundcolor="rgb(200, 200, 230)",
                                       gridcolor="white",
                                       showbackground=True,
                                       zerolinecolor="white"),
                             yaxis=dict(backgroundcolor="rgb(230, 200,230)",
                                       gridcolor="white",
                                       showbackground=True,
                                       zerolinecolor="white"),
                             zaxis=dict(backgroundcolor="rgb(230, 230,200)",
                                       gridcolor="white",
                                       showbackground=True,
                                       zerolinecolor="white")),
                  title='Customized 3D Scatter Plot')
()

Interactive 3D graphics

Plotly also supports the creation of interactive three-dimensional graphics, allowing users to explore data through mouse interaction. Here is an example of an interactive scatter plot:

# Create an interactive scatter plotfig = (data=[go.Scatter3d(x=x_data, y=y_data, z=z_data, mode='markers')])
fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
                  title='Interactive 3D Scatter Plot')
()

By hovering over the data point, users can view the specific values ​​of each data point, allowing for a deeper understanding of the data.

Export graphics

Once you have created a satisfactory 3D graphics, you can export them as static images or interactive HTML files for easy sharing and display. Plotly provides convenient export features, allowing you to easily save graphics to local files.

# Export the graphics as a static imagefig.write_image("3d_plot.png")

# Export the graphics as an interactive HTML filefig.write_html("3d_plot.html")

Explore more features

In addition to the features introduced in this article, Plotly also provides many other powerful features, such as animations, sub-pictures, camera controls, etc., which can further enhance and customize your 3D graphics. You can dig deeper into these features by consulting official documentation or referring to online tutorials and applying them to your project.

Summarize

Through this article, we learn how to use Python and Plotly libraries to draw various types of 3D graphics, including scatter plots, surface plots, wireframes, and bar charts. We learned about the basic steps and code examples needed to draw each graphic, and explored how to customize the graphic style, create interactive graphic, and export the graphic as a static image or an interactive HTML file. With these tips and features, we can easily create attractive and practical three-dimensional graphics in the field of data visualization, allowing us to better understand and analyze data. Whether in scientific research, engineering applications or data analysis, 3D graphics are a powerful tool that helps us discover patterns and relationships between data and demonstrate research results and insights. By constantly exploring and applying the functions of Python and Plotly libraries, we can further improve the effectiveness and efficiency of data visualization, bringing more value and achievements to our work and projects.

The above is the detailed content of the method of using Python and Plotly to draw various types of 3D graphics. For more information about Python Plotly to draw 3D graphics, please follow my other related articles!