在 matplotlib 中可以轻松绘制 3D 图形。接下来讨论一些重要且常用的 3D 图。
1 画点代码
<span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>from</strong></span> mpl_toolkits.mplot3d <span style="color:#333333"><strong>import</strong></span> axes3d
<span style="color:#333333"><strong>import</strong></span> matplotlib.pyplot <span style="color:#333333"><strong>as</strong></span> plt
<span style="color:#333333"><strong>from</strong></span> matplotlib <span style="color:#333333"><strong>import</strong></span> style
<span style="color:#333333"><strong>import</strong></span> numpy <span style="color:#333333"><strong>as</strong></span> np
<span style="color:#888888"># setting a custom style to use</span>
style.use(<span style="color:#880000">'ggplot'</span>)
<span style="color:#888888"># create a new figure for plotting</span>
fig = plt.figure()
<span style="color:#888888"># create a new subplot on our figure</span>
<span style="color:#888888"># and set projection as 3d</span>
ax1 = fig.add_subplot(<span style="color:#880000">111</span>, projection=<span style="color:#880000">'3d'</span>)
ax1.scatter(x, y, z, c = <span style="color:#880000">'m'</span>, marker = <span style="color:#880000">'o'</span>)
<span style="color:#888888"># defining x, y, z co-ordinates</span>
x = np.random.randint(<span style="color:#880000">0</span>, <span style="color:#880000">10</span>, size = <span style="color:#880000">20</span>)
y = np.random.randint(<span style="color:#880000">0</span>, <span style="color:#880000">10</span>, size = <span style="color:#880000">20</span>)
z = np.random.randint(<span style="color:#880000">0</span>, <span style="color:#880000">10</span>, size = <span style="color:#880000">20</span>)
<span style="color:#888888"># plotting the points on subplot</span>
<span style="color:#888888"># setting labels for the axes</span>
ax1.set_xlabel(<span style="color:#880000">'x-axis'</span>)
ax1.set_ylabel(<span style="color:#880000">'y-axis'</span>)
ax1.set_zlabel(<span style="color:#880000">'z-axis'</span>)
<span style="color:#888888"># function to show the plot</span>
plt.show()
</span></span>
2 输出
上述程序的输出将为您提供一个可以旋转或放大绘图的窗口。这是屏幕截图:
现在让我们试着理解这段代码的一些要点。
from mpl_toolkits.mplot3d import axes3d
1)这是在 3-D 空间上绘图所需的模块。
ax1 = fig.add_subplot(111, projection='3d')
2)在图形上创建一个子图并将投影参数设置为 3d。
ax1.scatter(x, y, z, c = 'm', marker = 'o')
3)使用 函数来绘制 XYZ 平面中的点。 .scatter()
3 画线代码