我有一个Python列表,表示一系列线段,包含形式(x,y,z,颜色)的元组,其中x,y,z是浮点数,颜色是描述线应该是什么颜色的字符串我(或者更确切地说,我正在使用的mecode库)将坐标粘贴到numpy数组X,Y和Z中。
当我在matplotlib中使用:
渲染此列表时from mpl_toolkits.mplot3d import Axes
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(X, Y, Z)
3D查看器表现相当不错,但我当然没有任何颜色。
但是当我使用Line colour of 3D parametric curve in python's matplotlib.pyplot建议的代码时:
for i in range(len(X)-1):
ax.plot(X[i:i+2], Y[i:i+2], Z[i:i+2],
color=self.position_history[i][3])
3D渲染中的事情变慢了。
我想知道好的Pythonic方法是迭代具有相同颜色的列表元素,这样我就可以减少对ax.plot的调用次数。我假设这会让事情变得更快。
答案 0 :(得分:1)
如果重复调用绘图是个问题,那么如果按颜色对所有点进行分组并将它们全部渲染,您将获得加速。一种方法(快速和脏,以便您可以检查这是否使您的渲染更快)在这里:
from collections import defaultdict
points = defaultdict(list) # will have a list of points per color
for i in range(len(X)):
color = self.position_history[i][3]
if len(points[color])==0:
points[color].append([]) # for the X coords
points[color].append([]) # for the Y coords
points[color].append([]) # for the Z coords
points[color][0].append(X[i])
points[color][1].append(Y[i])
points[color][2].append(Z[i])
# now points['red'] has all the red points
for color in points.keys():
pts = points[color]
ax.plot(pts[0],pts[1],pts[2],
color=color)