2014-12-04 112 views
0
#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; 

此圖在每次迭代中生成一組點。但在所有迭代結束時,不可能區分不同世代的點。那麼是否有可能以不同的方式爲每個生成點着色?也應該有可能進行n次迭代。每次迭代更改3D散點圖的顏色

回答

1

添加顏色列表並重復遍歷它們:

例如,添加這些行到你的代碼

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 

您的代碼將是:

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;