【问题标题】:Change marker/color in 3D scatter plot based on condition根据条件更改 3D 散点图中的标记/颜色
【发布时间】:2019-03-27 10:56:49
【问题描述】:

我想用 matplotlib 在 Python 中做一个 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()

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

【问题讨论】:

  • 您的 if 条件没有完成任何事情 - 在这两种情况下,您仍在绘制整个系列。而是为每个条件创建单独的 XY

标签: python matplotlib scatter-plot


【解决方案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()

【讨论】:

    【解决方案2】:

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

    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')
    

    【讨论】:

    • 我正在考虑这样的事情,但无法让它发挥作用。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2014-09-24
    • 2021-07-13
    • 2011-07-26
    • 1970-01-01
    相关资源
    最近更新 更多