如何在 Python 中制作 3D 散点图?
matplotlibserver side programmingprogramming
要获得 3D 图,我们可以使用 fig.add_subplot(111,projection='3d') 方法来实例化轴。之后,我们可以使用 scatter 方法在 x、y 和 z 轴上绘制不同的数据点。
步骤
创建一个新图形,或激活现有图形。
将 `~.axes.Axes` 添加到图形中作为子图排列的一部分,其中 nrows = 1、ncols = 1、index = 1 且投影为"3d"。
迭代标记列表 xs、ys 和 zs,以制作散点。
使用 set_xlabel、y_label 和 z_label 方法设置 x、y 和 z 标签。
使用 plt.show() 方法绘制图。
示例
import matplotlib.pyplot as plt import numpy as np np.random.seed(1000) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') n = 100 for m, zl, zh in [('o', -50, -25), ('^', -30, -5)]: xs = (32 - 23) * np.random.rand(n) + 23 ys = (100 - 0) * np.random.rand(n) zs = (zh - zl) * np.random.rand(n) + zl ax.scatter(xs, ys, zs, marker=m) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show()