Search code examples
pythonscatter-plot

Making a 3D scatterplot that changes colors depending on value of Z


I want to make a simple loop that makes a 3D scatterplot. but, i want two colors, depending on value of z in my data.

I know i am doing something wrong with my loop, but can anyone tell me what is wrong?

My code looks like this

import matplotlib.pyplot as plt
import numpy as np

data = np.loadtxt('Koordinater/Co_sektions.txt')
z = data[:,2]
fig = plt.figure(figsize=(10,7))
ax = plt.axes(projection = "3d")
ax.set_zlim(0, 27000)

d1 = range(0,len(data),1)

for i in d1:
    if z[i] <= 1000:
        ax.scatter3D(data[:,1], data[:,0], data[:,2],color='red')
    else:
        ax.scatter3D(data[:,1], data[:,0], data[:,2])
plt.show()

My data looks like

     0  -14450       0
  1583  -14450     902
  1583   14450     902
     0   14450       0
  3166   14450    1704
  3166  -14450    1704
  4749  -14450    2414
  4749   14450    2414
  6332  -14450    3036
  6332   14450    3036
  7915   14450    3576

Solution

  • You could have split the lists into 2 lists, but this is better:

    i have not used your data (created my own for simplicity), but you can do something like this:

    import matplotlib.pyplot as plt
    
    
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')
    import numpy as np
    
    
    x = np.array([1,2,3,4,5])
    y = np.array([10,20,30,40,50])
    z = np.array([100,200,300,400,500])
    
    c = 250 # a threshold criteria
    ax.scatter(x[z>c], y[z>c], z[z>c], s=100, c='r', marker='o')
    ax.scatter(x[z<=c], y[z<=c], z[z<=c], s=100, c='b', marker='x')
    
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    
    
    plt.show()
    
    

    which gives this:

    enter image description here