基于仅更新绘图中颜色的动画

Cup*_*tor 6 python plot numpy matplotlib

我有一个由大量线条组成的情节.在每一步中,线条的颜色应该在动画中得到更新,但在线条上进行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()
Run Code Online (Sandbox Code Playgroud)

另外我无法与动画艺术家合作!我用画画.动画线有什么问题

现在将这些10增加到100会使程序非常缓慢:

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()
Run Code Online (Sandbox Code Playgroud)

正如我所说,我希望与动画并排运行.因此我更喜欢把它变成动画.我认为这至少会在动画开始后解决滞后问题但现在我定义它的方式,它不起作用.

Joe*_*ton 5

这是最容易使用的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)
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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述