2

I've got a Python list representing a series of line segments that contains tuples of the form (x, y, z, color) where x, y, z are floats and color is a string describing what color the line should be in. I (or rather, the mecode library I'm using) is sticking the coordinates into numpy arrays X, Y, and Z.

When I render this list in matplotlib with:

from mpl_toolkits.mplot3d import Axes
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(X, Y, Z)

The 3D viewer performs rather well, but of course I don't get any colors.

But when I use the code suggested by 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])

Things get much slower in the 3D render.

I am wondering what the nice Pythonic way is to iterate over the list elements that have the same color, so that I can reduce the number of calls to ax.plot. I'm making the assumption that this will make things faster.

Community
  • 1
  • 1
razeh
  • 2,725
  • 1
  • 20
  • 27
  • You could add the color to a dictionary, everytime you get a color you check if it exists in the dictionary, if yes, you skip it, else you iterate over it – Beginner Nov 15 '14 at 19:59

1 Answers1

1

If the repeated calls to plot are the problem, then you will get a speedup if you group all the points by color and render them all together. A way to do this (quick and dirty, so that you can check if this makes your rendering faster at all) is here:

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)
razeh
  • 2,725
  • 1
  • 20
  • 27
grasshopper
  • 3,988
  • 3
  • 23
  • 29