仅根据绘图中的颜色更新的动画
我有一个由大量线组成的图。在每一步中,线条的颜色都应在动画中更新,但是在线条上进行for循环似乎确实很昂贵。有什么更好的方法吗?
这是我的代码:
import numpy as np
lines=[]
from matplotlib import pyplot as plt
import matplotlib.animation as animation
#initial plot
fig=plt.figure()
ax=plt.subplot(1,1,1)
for i in range(10):
lines.append([])
for j in range(10):
lines[i].append(ax.plot([i,j],color='0.8'))
lines=np.asarray(lines)
##Updating the colors 10 times
im=[]
for steps in range(10):
colors=np.random.random(size=(10,10))
for i in range(10):
for j in range(10):
lines[i,j][0].set_color(str(colors[i,j]))
plt.draw()
# im.append(ax)
plt.pause(.1)
#ani = animation.ArtistAnimation(fig, im, interval=1000, blit=True,repeat_delay=1000)
plt.show()
另外,我无法与动画艺术家合作!我用平局。动画行有什么问题
现在将那些10s增加到100s会使程序非常慢:
import numpy as np
lines=[]
from matplotlib import pyplot as plt
import matplotlib.animation as animation
#initial plot
fig=plt.figure()
ax=plt.subplot(1,1,1)
for i in range(100):
lines.append([])
for j in range(100):
lines[i].append(ax.plot([i,j],color='0.8'))
lines=np.asarray(lines)
##Updating the colors 10 times
im=[]
for steps in range(10):
colors=np.random.random(size=(100,100))
for i in range(100):
for j in range(100):
lines[i,j][0].set_color(str(colors[i,j]))
plt.draw()
# im.append(ax)
plt.pause(.1)
#ani = animation.ArtistAnimation(fig, im, interval=1000, blit=True,repeat_delay=1000)
plt.show()
正如我说的,我想与动画并排运行。因此,我更喜欢将其制作成动画。我认为这至少可以在动画开始之后解决滞后问题,但是现在按照我定义它的方式,它是行不通的。
-
LineCollection
为此最容易使用。这样,您可以将所有颜色设置为单个阵列,并且通常可以获得更好的绘图性能。更好的性能主要是因为集合是在matplotlib中绘制许多相似对象的优化方法。在这种情况下,避免嵌套循环来设置颜色实际上是次要的。
考虑到这一点,请尝试以下方法:
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()