hari hari - 6 months ago 26
Python Question

Change color of 3D scatterplot each iteration

#3d dynamic scatterplot
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time

plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
s=0
a=1
b=2
for i in range(0, 10):
s=a+b
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
x = np.random.rand(5, 3)
y = np.random.rand(5, 3)
z = np.random.rand(5, 3)
#ax.cla()
ax.scatter(x[:, 0], y[:, 1], z[:, 2])
plt.draw()
time.sleep(1) #make changes more apparent/easy to see
a=a+1
b=b+2
if s>10:
break;


This plot generates a set of points each iteration. But at the end of all iterations, it is not possible to distinguish points of different generations. So is it possible to color each generation points differently? Also it should be possible for n number of iterations.

Answer

Add a list of colours and iterate through them:

e.g. add these lines to your code

colors = ['#8ffe09','r','#0033ff','#003311','#993333','#21c36f','#c46210','#ed3cca','#ffbf00','g','#000000'] # a list of colours


ax.scatter(x[:, 0], y[:, 1], z[:, 2],color=colors[a-1]) # use the color kwarg

Your code would be:

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
colors = ['#8ffe09','r','#0033ff','#003311','#993333','#21c36f','#c46210','#ed3cca','#ffbf00','g','#000000']
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
s=0
a=1
b=2
for i in range(0, 10):   
    s=a+b
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
    ax.set_zlabel('Z axis')
    x = np.random.rand(5, 3) 
    y = np.random.rand(5, 3)
    z = np.random.rand(5, 3)
    #ax.cla()    
    ax.scatter(x[:, 0], y[:, 1], z[:, 2],color=colors[a-1])
    plt.draw()
    time.sleep(1)   #make changes more apparent/easy to see
    a=a+1
    b=b+2
    if s>10:
         break;