Python中动画3D散点图的单独颜色

2024-04-20 10:07:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个动画三维散点图,能够将动态数量的类绘制为不同的颜色。这是一种尝试。我已经包括了整个代码,以防有用,并用一排星星标记了故障点:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from random import uniform

x_arr,y_arr,depth_arr,time_arr,ml_arr,cluster_arr = np.loadtxt(data, unpack=5, usecols=(0, 1, 2, 5, 6))
class Point:
        def __init__(self,x,y,depth,time,cluster):
                self.x=x
                self.y=y
                self.depth=depth
                self.time=time
                self.cluster=cluster
points = []
for i in range(0,len(x_arr)):
        points.append(Point(x_arr[i],y_arr[i],depth_arr[i],time_arr[i],cluster_arr[i]))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim(min(x_arr), max(x_arr))
ax.set_ylim(min(y_arr), max(y_arr))
ax.set_zlim(min(depth_arr), max(depth_arr))
colors_1 = plt.cm.jet(np.linspace(0,max(cluster_arr),max(cluster_arr)+1))
colors = colors_1.reshape(-1,4)
def plot_points(time):
        x = []
        y = []
        z = []
        clust = []
        points_cp = list(np.copy(points))
        for i in range(0,(int(max(cluster_arr))+1)):
                for event in points_cp:
                        if event.cluster == i:
                                if event.time < time:
                                        points_cp.remove(event)
                                elif event.time <= time + 86400:
                                        x.append(event.x)
                                        y.append(event.y)
                                        z.append(event.depth)
                                        clust.append(event.cluster)
                                        points_cp.remove(event)
# **************************************************************
        color_ind = 0
        first_ind = 0
        last_ind = 0
        for i in range(0,len(x)):
                if clust[i] != color_ind:
                        last_ind = i
                        for i in range(0,len(x)):
                                ax.scatter(x[first_ind:last_ind],y[first_ind:last_ind],z[first_ind:last_ind],c=colors[int(color_ind)])
                                color_ind = clust[i]
                                first_ind = i

time = np.linspace(min(time_arr),max(time_arr),100)

ani = animation.FuncAnimation(fig,plot_points,time)
plt.show()

这将为我提供具有正确颜色的打印,但一旦打印出一个点,它将在整个动画中保持不变

我也尝试过set_x、set_color等,但这不适用于循环(它会随着每次迭代而更新,因此实际上只绘制最后一个类),我需要使用for循环来容纳数量可变的类。我曾尝试使用具有固定范围的colormap,但没有成功,因为colormapping无法与plot函数一起使用,并且我无法让其余代码与散布函数一起使用

提前感谢您的帮助,如果代码有点不可靠,我深表歉意。我对这个很陌生


Tags: inimportselfeventfortimenpax