根据条件更改三维散点图中的标记/颜色

问题描述 投票:0回答:2

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

问题是我仍然使用两种标记/颜色绘制所有值,我也知道为什么会出现这种情况,但我并没有深入到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()

也许解决方案也是我尚未学到的东西,但在我看来,这应该不是很难。

python matplotlib scatter-plot
2个回答
1
投票

您可以使用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()

enter image description here


0
投票

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

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')
© www.soinside.com 2019 - 2024. All rights reserved.