Matplotlib3D color based points on their Z axis value
<p>I am currently scattering points in a 3D graph. My X,Y and Z are lists (len(Z)=R). However, I would like to give them a color based on their Z value. For example if Z>1 the color would be red, Z>2 blue Z>3 pink and so on. My current code is:</p>

<pre><code>from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X,Y,Z,for k in range (R): if Z&gt;1: color=['red']) 
plt.show()
</code></pre>

<p>If you see the gallery, you will find the answer. You need to pass an array to <code>c=colors</code>. See these: <a href="http://matplotlib.org/examples/mplot3d/scatter3d_demo.html" rel="nofollow">1</a>, <a href="http://matplotlib.org/examples/pie_and_polar_charts/polar_scatter_demo.html" rel="nofollow">2</a>.</p>

<pre><code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def randrange(n, vmin, vmax):
    return (vmax - vmin)*np.random.rand(n) + vmin


fig = plt.figure(figsize=(8,5))
ax = fig.add_subplot(111, projection='3d')
n = 100
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, 0, 50)
scat = ax.scatter(xs, ys, zs, c=zs, marker="o", cmap="viridis")
plt.colorbar(scat)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
</code></pre>

<p><a href="http://i.stack.imgur.com/Vf9zp.png" rel="nofollow"><img src="http://i.stack.imgur.com/Vf9zp.png" alt="enter image description here"></a></p>

python matplotlib