Python has become an indispensable tool in today's data analytics and visualization. Its powerful data processing capabilities and rich visualization library enable data scientists and engineers to easily create complex and beautiful charts. Among them, Plotly is a high-level drawing library, especially good at creating interactive and 3D graphics. This article will introduce in detail how to use Python and Plotly to draw 3D graphics, including 3D coordinate systems, surface drawings, scatter plots and other styles, and provides rich code examples and cases to help newbies get started quickly.
1. Introduction to Plotly
Plotly is an open source drawing library that provides rich drawing functions, including static and interactive graphics, 3D graphics, etc. Plotly is divided into two main parts: Plotly Express and Plotly Graph Objects. Plotly Express is an advanced interface for quickly creating common chart types; while Plotly Graph Objects provides a more underlying interface that allows users to create custom charts.
2. Preparation
Before you start drawing 3D graphics, you need to make sure that the Plotly library is installed. You can use the pip command to install:
pip install plotly
In addition, we also need to use the NumPy library to generate sample data. If you haven't installed NumPy yet, you can use the following command to install:
pip install numpy
3. Draw 3D coordinate system
Drawing a 3D coordinate system is the basis for creating 3D graphics. Here is a simple example code showing how to create a 3D coordinate system with X, Y, and Z axes.
import plotly.graph_objects as go import numpy as np # Create a graphical objectfig = () # Add 3D axisfig.add_trace(go.Scatter3d( x=[0, 10], y=[0, 0], z=[0, 0], mode='lines', line=dict(color='red', width=2) )) fig.add_trace(go.Scatter3d( x=[0, 0], y=[0, 10], z=[0, 0], mode='lines', line=dict(color='green', width=2) )) fig.add_trace(go.Scatter3d( x=[0, 0], y=[0, 0], z=[0, 10], mode='lines', line=dict(color='blue', width=2) )) # Set the axis labelfig.update_layout( scene=dict( xaxis_title='X-axis', yaxis_title='Y-axis', zaxis_title='Z-axis' ) ) # Show graphics()
In this code, we first create a graphical object fig, and then use go.Scatter3d to add three lines, representing the X-axis, Y-axis and Z-axis. Finally, the label of the axis is set through the update_layout method.
4. Draw 3D surface diagram
3D surface diagrams are a common way to display three-dimensional data. Here is a sample code for drawing a 3D surface diagram using Plotly.
import plotly.graph_objects as go import numpy as np # Generate sample datax = (-5, 5, 100) y = (-5, 5, 100) x, y = (x, y) z = ((x**2 + y**2)) # Create a graphic object and add a 3D surface diagramfig = (data=[(z=z, x=x, y=y)]) # Set the graphic title and axis labelfig.update_layout( title='3D Surface Diagram', scene=dict( xaxis_title='X-axis', yaxis_title='Y-axis', zaxis_title='Z-axis' ) ) # Show graphics()
In this code, we first generate a 100x100 grid data using NumPy, and then calculate the z-value of each grid point (using a sine function). Next, we created a graph object fig and added a 3D surface diagram using it. Finally, the update_layout method is used to set the title of the figure and the label of the coordinate axis.
5. Draw 3D scatter plots
3D scatter plots are another way to display three-dimensional data. Here is a sample code for drawing a 3D scatter plot using Plotly.
import plotly.graph_objects as go import numpy as np # Generate sample data(0) x = .standard_normal(100) y = .standard_normal(100) z = .standard_normal(100) # Create a graphical object and add a 3D scatter plotfig = (data=[go.Scatter3d(x=x, y=y, z=z, mode='markers')]) # Set the graphic title and axis labelfig.update_layout( title='3D scatter plot', scene=dict( xaxis_title='X-axis', yaxis_title='Y-axis', zaxis_title='Z-axis' ) ) # Show graphics()
In this code, we first use NumPy to generate 100 random numbers that obey the standard normal distribution, as data for the x, y, and z axes. We then created a graphical object fig and added a 3D scatter plot using go.Scatter3d. Finally, the update_layout method is used to set the title of the figure and the label of the coordinate axis.
6. Draw a 3D histogram
3D histogram is a way to show the distribution of three-dimensional data. Here is a sample code for drawing a 3D histogram using Plotly.
import plotly.graph_objects as go import numpy as np # Generate sample datax = (0, 1, 1000) y = (0, 1, 1000) z = (0, 1, 1000) # Calculate histogram datahist, xedges, yedges = np.histogram2d(x, y, bins=20) # Generate a grid of histogramsxpos, ypos = (xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij") xpos = () ypos = () zpos = np.zeros_like(xpos) # Set the size of the histogramdx = dy = np.ones_like(zpos) * 0.5 dz = () # Create a graphic object and add a 3D histogramfig = (data=[go.Bar3d(x=xpos, y=ypos, z=zpos, dx=dx, dy=dy, dz=dz)]) # Set the graphic title and axis labelfig.update_layout( title='3D histogram', scene=dict( xaxis_title='X-axis', yaxis_title='Y-axis', zaxis_title='frequency' ) ) # Show graphics()
In this code, we first generate 1000 random numbers that obey the standard normal distribution, as data for the x, y, and z axes. We then compute the data of the two-dimensional histogram using the np.histogram2d function and generate a grid of histograms. Next, we created a graphical object fig and added a 3D histogram using go.Bar3d. Finally, the update_layout method is used to set the title of the figure and the label of the coordinate axis.
7. Case: Drawing a map of the earth's surface
As a more complex case, we will use Plotly to map a surface of the earth. This case will show how to use Plotly's 3D drawing capabilities to create an interactive Earth model.
import plotly.graph_objects as go import numpy as np import as plt from PIL import Image # Read Earth Imageimg = ('') img = ((360, 180)) # Resize the image to match the resolution of the globeimg_array = (img) / 255.0 # Convert an image to an array of floating point numbers between 0-1 # Generate Earth's surface coordinatesphi = (0, , 180) theta = (0, 2 * , 360) phi, theta = (phi, theta) x = (phi) * (theta) y = (phi) * (theta) z = (phi) # Create a graphic object and add a surface map of the earthfig = (data : python [( z=img_array, x=(), y=(), colorscale='Viridis' # Use Viridis color maps to enhance visual effects)]) # Set the graphic title and axis labelfig.update_layout( title='Earth surface map', scene=dict( xaxis_title='longitude', yaxis_title='latitude', zaxis_title='high', camera=dict( eye=dict(x=1.25, y=1.25, z=1.25) # Adjust the camera position to better view the earth ) ) ) # Show graphics()
In this code, we first read an image of the Earth's surface and resize it to 360x180 pixels to match the resolution of the globe. We then convert the image to an array of floating point numbers between 0-1 so that Plotly can render the colors correctly.
Next, we generate a coordinate grid of the earth's surface, where phi represents latitude and theta represents longitude. Through the sum function, we convert the latitude and longitude coordinates to the x, y, and z values under the Cartesian coordinate system.
We then created a graphical object fig and added the Earth surface map using it. Note that we take the pixel values of the image as data on the z-axis, while the data on the x and y-axis are Cartesian coordinates of the earth's surface. In addition, we also used the colorscale='Viridis' parameter to enhance the visual effect, making the earth's surface richer and three-dimensional.
Finally, we set the title and the label of the axis of the graph through the update_layout method and adjust the position of the camera to better view the earth.
When you run this code, you will see an interactive 3D map of the Earth's surface. You can view different parts of the earth by dragging, rotating, and scaling, and observe the color and texture of its surface.
8. Summary
This article details how to draw 3D graphics using Python and Plotly, including 3D coordinate systems, surface diagrams, scatter diagrams, histograms, and earth surface diagrams. With these sample codes and cases, you can quickly grasp Plotly's 3D drawing capabilities and apply them to your own data analysis and visualization projects.
It should be noted that although Plotly provides powerful 3D drawing capabilities, drawing complex 3D graphics may require some computing resources and time. Therefore, in practical applications, you need to select appropriate drawing methods and parameters based on the size and complexity of the data to ensure the rendering effect and performance of the graphics.
In addition, Plotly supports integration with other Python libraries (such as Pandas, Matplotlib, etc.), which makes it easier for you to preprocess and visualize data. Therefore, after mastering Plotly's 3D drawing capabilities, you can further explore these integrations to improve your data analysis and visualization capabilities.
This is the end of this article about Python and Plotly implementing 3D graphics drawing. For more related content on Python Plotly drawing 3D graphics, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!