This article is shared from the Huawei Cloud Community " Plotly Drawing 3D Graphics " by Lemony Hug.
In the field of data visualization, 3D graphics are a powerful tool for showing complex relationships and structures between data. The Python language has a rich data visualization library, 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'll use Plotly's plotly.graph_objects
modules to create 3D graphics. We will also use numpy
the library to generate 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 stored in x_data
, y_data
and z_data
.
# Generate sample data np.random.seed(42) n_points = 100 x_data = np.random.rand(n_points) y_data = np.random.rand(n_points) z_data = np.random.rand(n_points) #Create a scatter plot fig = go.Figure(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') fig.show()
The above code will generate a simple three-dimensional scatter plot showing the distribution of randomly generated data points in three-dimensional space.
Draw surface plot
Next, we'll draw a surface plot. Suppose we have a function f(x, y)
and we want to visualize its surface in three dimensions.
# define function def f(x,y): return np.sin(x) * np.cos(y) # Generate grid data x_grid = np.linspace(0, 2*np.pi, 50) y_grid = np.linspace(0, 2*np.pi, 50) x_grid, y_grid = np.meshgrid(x_grid, y_grid) z_grid = f(x_grid, y_grid) #Create surface plot fig = go.Figure(data=[go.Surface(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') fig.show()
The above code will generate a 3D surface plot showing the surface of the function.
Draw wireframes
Finally, we will draw a wireframe showing the continuity of the data.
# Generate wireframe data theta = np.linspace(-4*np.pi, 4*np.pi, 100) z_line = np.linspace(-2, 2, 100) x_line = z_line * np.sin(theta) y_line = z_line * np.cos(theta) #Create wireframe fig = go.Figure(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') fig.show()
The above code will generate a 3D graphic showing the wireframe.
Through the above examples, we have shown how to use Python and Plotly to draw various types of three-dimensional graphics. You can further customize these graphics to suit your needs and explore the richer features in the Plotly library. Happy plotting!
Draw 3D bar graph
In addition to scatter plots, surface plots, and wireframe plots, we can also draw 3D bar charts to show differences and relationships between data.
# Generate sample data categories = ['A', 'B', 'C', 'D'] values = np.random.randint(1, 10, size=(len(categories), len(categories))) x_bar, y_bar = np.meshgrid(np.arange(len(categories)), np.arange(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 chart bar_heights = values.flatten() #Create 3D bar chart fig = go.Figure(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') fig.show()
The above code will generate a three-dimensional bar chart showing the relationship between various categories and values.
Custom graphic style
Plotly provides a wealth of customization options to adjust the style, layout, and appearance of graphics. You can modify the color, line type, label and other properties of the graphics as needed to meet specific visualization needs.
# Custom graphic style fig.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') fig.show()
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 plot fig = go.Figure(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') fig.show()
By hovering the mouse over the data points, users can view the specific numerical value of each data point to gain a deeper understanding of the data.
Export graphics
Once you've created a 3D graphic you're happy with, you can export it as a static image or interactive HTML file for easy sharing and presentation. Plotly provides a convenient export function, allowing you to easily save graphics to local files.
#Export graphics as static images fig.write_image("3d_plot.png") # Export graphics as interactive HTML files fig.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 animation, sprites, camera control, etc., to further enhance and customize your three-dimensional graphics. You can learn more about these features and apply them to your projects by consulting the official documentation or referring to online tutorials.
Summarize
Through this article, we learned how to use Python and the Plotly library to draw various types of three-dimensional graphics, including scatter plots, surface plots, wireframe plots, and bar charts. We learned the basic steps and code examples required to draw each type of graph, and explored how to customize graph styles, create interactive graphs, and export graphs as static images or interactive HTML files. With these techniques and features, we can easily create attractive and useful 3D graphics in the field of data visualization to better understand and analyze data. Whether in scientific research, engineering applications, or data analysis, 3D graphics are powerful tools that help us discover patterns and relationships between data, and present research results and insights. By continuously 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.
Click to follow and learn about Huawei Cloud’s new technologies as soon as possible~
Microsoft's China AI team collectively packed up and went to the United States, involving hundreds of people. How much revenue can an unknown open source project bring? Huawei officially announced that Yu Chengdong's position was adjusted. Huazhong University of Science and Technology's open source mirror station officially opened external network access. Fraudsters used TeamViewer to transfer 3.98 million! What should remote desktop vendors do? The first front-end visualization library and founder of Baidu's well-known open source project ECharts - a former employee of a well-known open source company that "went to the sea" broke the news: After being challenged by his subordinates, the technical leader became furious and rude, and fired the pregnant female employee. OpenAI considered allowing AI to generate pornographic content. Microsoft reported to The Rust Foundation donated 1 million US dollars. Please tell me, what is the role of time.sleep(6) here?