Animation based on only updating colours in a plot
It's easiest to use a LineCollection
for this. That way you can set all of the colors as a single array and generally get much better drawing performance.
The better performance is mostly because collections are an optimized way to draw lots of similar objects in matplotlib. Avoiding the nested loops to set the colors is actually secondary in this case.
With that in mind, try something more along these lines:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
import matplotlib.animation as animation
lines=[]
for i in range(10):
for j in range(10):
lines.append([(0, i), (1, j)])
fig, ax = plt.subplots()
colors = np.random.random(len(lines))
col = LineCollection(lines, array=colors, cmap=plt.cm.gray, norm=plt.Normalize(0,1))
ax.add_collection(col)
ax.autoscale()
def update(i):
colors = np.random.random(len(lines))
col.set_array(colors)
return col,
# Setting this to a very short update interval to show rapid drawing.
# 25ms would be more reasonable than 1ms.
ani = animation.FuncAnimation(fig, update, interval=1, blit=True,
init_func=lambda: [col])
# Some matplotlib versions explictly need an `init_func` to display properly...
# Ideally we'd fully initialize the plot inside it. For simplicitly, we'll just
# return the artist so that `FuncAnimation` knows what to draw.
plt.show()
If you want to speed up a for loop, there are several good ways to do that. The best one for what you are trying to do, generator expressions, is probably like this:
iterator = (<variable>.upper() for <samevariable> in <list or other iterable object>)
(for more specific information on these there is documentation at http://www.python.org/dev/peps/pep-0289/ and https://wiki.python.org/moin/Generators)
There are also other, non-for loop ways to update color, but they are unlikely to be any faster than a generator. You could create some form of group for the lines, and call something like:
lines.update()
on all of them.