1Function mpl_toolkits.mplot3d
introduction
mpl_toolkits.mplot3d
It is a submodule in the Matplotlib library, used to draw and visualize three-dimensional graphics, including three-dimensional scatter plots, surface plots, line plots, etc. It provides rich functionality to create and customize 3D graphics. Here are mpl_toolkits.mplot3d
the main features and functionality of :
3D scatter plot : Through
scatter
the function, you can draw a three-dimensional scatter plot to display the distribution and relationship of three-dimensional data points.3D surface plot : Using
plot_surface
the function, you can create a 3D surface plot for visualizing the surface shape of 3D data. This is useful for showing the three-dimensional nature of functions.3D line graph :
plot
The function allows you to draw a three-dimensional line graph to represent the connection relationship between data points. This is useful for showing trends in data over time or other variables.3D Bar Chart :
bar3d
The function allows you to create a three-dimensional bar chart that compares different categories or groups of data.3D scatter plot markers and colors : You can customize the scatter plot marker shapes and colors based on the characteristics of your data to distinguish different data points.
3D coordinate axis customization : You can set and customize the coordinate axes of the 3D chart, including adding labels, setting scales and ranges, etc.
Graph style customization : You can set the style of the graph, including title, legend, background color, line style and color, etc., to make the graph more attractive and readable.
3D projection :
mpl_toolkits.mplot3d
Supports different types of 3D projection, including perspective projection and orthogonal projection, to meet different visualization needs.Animation and interactivity : You can add animation effects or interactive elements to your 3D plots to better explore your data.
Multi-graph combination : You can combine multiple graphs of different types in the same 3D graph to display multiple data series.
Save the drawing : Finally, you can save the drawn 3D drawing as an image file for use in documents or to share with others.
In short, mpl_toolkits.mplot3d
the submodule provides Matplotlib with powerful three-dimensional visualization tools that can be used to visualize and analyze three-dimensional data. Depending on your needs, you can choose different graph types and styles to present your data to better understand and communicate your findings.
In the Matplotlib mpl_toolkits.mplot3d
module, the general process of drawing 3D graphs includes the following steps:
(1) Import necessary libraries and modules:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
(2) Create a 3D graphics drawing object:
fig = plt.figure()
(3) Create a 3D subgraph:
ax = fig.add_subplot(111, projection='3d')
(4) Prepare data: Define X, Y and Z data, which will be represented in the 3D graph.
-
Use the corresponding 3D plotting functions to plot the data, for example:
- Scatter plot:
ax.scatter(x, y, z, c='color', marker='marker_style', label='label')
- Surface plot:
ax.plot_surface(X, Y, Z, cmap='colormap')
- line graph:
ax.plot(x, y, z, label='label')
- Bar chart:
ax.bar3d(x, y, z, dx, dy, dz, shade=True)
- Scatter plot:
(5) Add axis labels:
ax.set_xlabel('X轴标签')
ax.set_ylabel('Y轴标签')
ax.set_zlabel('Z轴标签')
(6) Add title:
plt.title('3D 图标题')
(7) Add legend (if needed):
ax.legend()
(8) Display graphics:
plt.show()
2 Draw a 3D scatter plot
In matplotlib's mpl_toolkits.mplot3d module, you can use the `scatter` function to draw various types of 3D scatter plots.
Here are some common 3D scatter plot types:
2.1 Draw a single color scatter plot
All scatter points use the same color. Color can be specified by setting the `c` parameter.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制单色散点图
ax.scatter(x, y, z, c='blue')
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()
2.2 Draw a colored scatter plot
Different scatter points can use different colors. The color of each scatter point can be specified by setting the `c` parameter to an array of the same length.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
colors = np.random.rand(100)
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制彩色散点图
ax.scatter(x, y, z, c=colors)
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()
2.3 Draw a scatter plot of size changes
The size of the scatter points can vary depending on a feature. The size of each scatter point can be specified by setting the `s` parameter to an array of the same length.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.random.rand(100) # x坐标
y = np.random.rand(100) # y坐标
z = np.random.rand(100) # z坐标
colors = np.random.rand(100) # 散点颜色
sizes = np.random.randint(low=50, high=200, size=100) # 散点大小
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制散点图
ax.scatter(x, y, z, c=colors, s=sizes, alpha=0.8)
# 设置坐标轴标签
ax.set_xlabel('X') # 设置x轴标签
ax.set_ylabel('Y') # 设置y轴标签
ax.set_zlabel('Z') # 设置z轴标签
# 显示图形
plt.show()
2.4 Draw a scatter plot of shape changes
The shape of the scatter points can change based on a feature. The shape of the scatter points can be specified by setting the `marker` parameter.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
markers = ['o', 's', '^', 'D']
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制形状变化散点图
for i in range(len(x)):
ax.scatter(x[i], y[i], z[i], marker=markers[i%len(markers)])
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()
3 Draw 3D line graph
Draw 3D line plots using the Axes3D object in the mpl_toolkits.mplot3d module.
3.1 Simple line graph
Use the `plot` function to draw simple curves.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.linspace(0, 1, 100)
y = np.sin(2 * np.pi * x)
z = np.cos(2 * np.pi * x)
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制简单线图
ax.plot(x, y, z)
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()
3.2 Draw multi-line graphs
Use the `plot` function to draw multiple lines and display them in the same chart.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
# 创建示例数据
t = np.linspace(0, 20, 100) # 时间或X轴数据
x1 = np.sin(t)
y1 = np.cos(t)
z1 = t
x2 = np.sin(t) + 2
y2 = np.cos(t) + 2
z2 = t
# 创建图形和子图
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制第一条线
ax.plot(x1, y1, z1, label='线1', color='blue', linestyle='-', linewidth=2)
# 绘制第二条线
ax.plot(x2, y2, z2, label='线2', color='red', linestyle='--', linewidth=2)
# 添加标题
plt.title('三维多线图示例')
# 添加坐标轴标签
ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.set_zlabel('Z轴')
# 添加图例
ax.legend()
# 显示图形
plt.show()
3.3 Drawing labeled line graphs
Use the `plot` function and add marker points on the line by setting the `marker` parameter.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.linspace(0, 1, 100)
y = np.sin(2 * np.pi * x)
z = np.cos(2 * np.pi * x)
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制带标记的线图
ax.plot(x, y, z, marker='o')
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()
3.4 Draw three-dimensional grid line diagram
Use the `plot_wireframe` function to draw a grid line plot in 3D space.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X ** 2 + Y ** 2))
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制立体网格线图
ax.plot_wireframe(X, Y, Z)
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()
3.5 Draw contour maps
Use the `contour` or `contourf` function to draw contours in 3D space.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制3D等高线图
ax.contour3D(X, Y, Z, 50, cmap='viridis')
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()
4 Draw a 3D bar chart
In matplotlib, due to mpl_toolkits.mplot3d
module limitations, there is no function for directly drawing 3D bar charts. However, you can use bar3d
the function to draw a similar 3D bar chart effect.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = [1, 2, 3, 4, 5] # x轴坐标位置
y = [1, 2, 3, 4, 5] # y轴坐标位置
z = [0, 3, 2, 5, 1] # z轴高度,即条形的高度
dx = dy = 0.8 # x和y方向的宽度
dz = z # 条形的高度
colors = ['red', 'green', 'blue', 'orange', 'purple'] # 颜色列表,一一对应于每个条形
# 创建图形和轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制3D条形图,并设置每个条形的颜色
for xi, yi, zi, color in zip(x, y, z, colors):
ax.bar3d(xi, yi, 0, dx, dy, zi, color=color)
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 显示图形
plt.show()