根据条件更改 3D 散点图中的 marker/color

Change marker/color in 3D scatter plot based on condition

我想在 Python 中使用 matplotlib 绘制 3D 散点图,其中例如点 > 5 显示为红色,其余为蓝色。

问题是我仍然使用 markers/colors 绘制所有值,我也知道为什么会这样,但我对 Python 的思考不够深入以解决此问题。

X = [3, 5, 6, 7,]
Y = [2, 4, 5, 9,]
Z = [1, 2, 6, 7,]

#ZP is for differentiate between ploted values and "check if" values

ZP = Z

for ZP in ZP:

    if ZP > 5:
        ax.scatter(X, Y, Z, c='r', marker='o')
    else:
        ax.scatter(X, Y, Z, c='b', marker='x')

plt.show()

也许解决方案也是我还没有学到的东西,但在我看来,让它工作应该不难。

为每个条件创建单独的点:

X1,Y1,Z1 = zip(*[(x,y,z) for x,y,z in zip(X,Y,Z) if z<=5])
X2,Y2,Z2 = zip(*[(x,y,z) for x,y,z in zip(X,Y,Z) if z>5])

ax.scatter(X1, Y1, Z1, c='b', marker='x')   
ax.scatter(X2, Y2, Z2, c='r', marker='o')

您可以只使用 NumPy 索引。由于 NumPy 已经是 matplotlib 的依赖项,您可以通过将列表转换为数组来使用数组索引。

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D 

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

X = np.array([3, 5, 6, 7])
Y = np.array([2, 4, 5, 9])
Z = np.array([1, 2, 6, 7])

ax.scatter(X[Z>5], Y[Z>5], Z[Z>5], s=40, c='r', marker='o')
ax.scatter(X[Z<=5], Y[Z<=5], Z[Z<=5], s=40, c='b', marker='x')

plt.show()