Specify color of each point in scatter plot (matplotlib)

Question:

I have a 3D Plot that I created using matplotlib, and I have a list of rbg values that correspond to each point.

I have the X, Y, and Z data, and then I have a “color list” of the form:

[ (r,g,b), (r,g,b), ... , (r,g,b) ]

to match each (x, y, z) point.

Right now, I have

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

ax.scatter(X, Y, Z)
plt.show()

What’s the appropriate way to incorporate those rgb tuples so that each point will be assigned a specific color?

Asked By: codycrossley

||

Answers:

I used a for loop to individually assign each color to each point. Here is my code:

X = [1, 2, 3]
Y = [2, 5, 8]
Z = [6, 4, 5]
colors=["#0000FF", "#00FF00", "#FF0066"]

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


for i in range(len(X)):
    ax.scatter(X[i], Y[i], Z[i], color=colors[i])
plt.show()

The for loop goes point by point (hence the [i] in front of each X,Y,Z value) and gives a color one by one. I used hex colors for my example, but you could probably use something else if you wanted.

Answered By: Camon

If you don’t want to use a for loop (which can be very slow for large lists) You can use the scatter command as is with an RGB color list, but you need to specify the colors as a vector of RGB (or RGBA) values between 0 and 1

X = [0, 1, 2]
Y = [0, 1, 2]
Z = [0, 1, 2]
C = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]])
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

ax.scatter(X, Y, Z, c = C/255.0)
plt.show()

3 colored points

Answered By: kmader

Here is an example where the colors are calculated instead of specified by a literal list.

import numpy as np
from matplotlib.pyplot import subplots

phi = np.linspace(0, 2*np.pi, 60)
x = np.sin(phi)
y = np.cos(phi)
rgb_cycle = (np.stack((np.cos(phi          ), # Three sinusoids,
                       np.cos(phi+2*np.pi/3), # 120° phase shifted,
                       np.cos(phi-2*np.pi/3)
                      )).T # Shape = (60,3)
             + 1)*0.5                         # scaled to [0,1].

fig, ax = subplots(figsize=(3,3))
ax.scatter(x,y, c=rgb_cycle, s=90)
fig.show()

color ring

Answered By: Rainald62