每次迭代更改 3D 散点图的颜色


#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 次迭代。

添加颜色列表并遍历它们:

例如,将这些行添加到您的代码中

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;

相关内容

  • 没有找到相关文章

最新更新