3
\$\begingroup\$

I am using numpy and matplotlib to do a statistical simulation. The simulation itself is pretty fast thanks to numPy vectorizatio, however the plotting is slow since I still use a for loop.

Here is the result:

enter image description here

Right now, I call matplotlib.pyplot.plt 10000 times - once for each tile in 100 × 100 square which can't possibly be optimal, but I can't think of how to do it better:

N = 100
for x in range(N):
 for y in range(N):
 plt.fill( myPath[x,y,0] ,myPath[x,y,1])

Let's say I stored all the varaibles in an numPy array myPath with shape (N,N,2,4) so that myPath[x,y,0] and myPath[x,y,1] give the x and y coordinates of the path.

How do I reduce the number of calls to plt in my visualization?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 2, 2014 at 21:32
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Wouldn't plt.fill(myPath[..., ..., 0], myPath[..., ..., 1]) without a loop do the trick? \$\endgroup\$ Commented Jun 3, 2014 at 13:50

1 Answer 1

4
\$\begingroup\$

Try using matplotlib's LineCollection class. Here's an example.

In your case, you might do:

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
ax = plt.gca()
pts = myPath.reshape((-1,2)) # make a matrix of (x,y) pairs
edges = LineCollection(pts)
ax.add_collection(edges)
plt.show()
answered Sep 24, 2014 at 22:22
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.