python - 循环更新帧时的 LineCollection 动画

标签 python matplotlib plot

下面的代码应该做同样的事情 here在动画期间更新线条颜色的位置。但是,颜色没有更新。这段代码的哪一部分是错误的?

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()

ims = []
for i in range(100):
    colors = np.random.random(len(lines))
    col.set_array(colors)
    ims.append([ax.add_collection(col)])
ani = animation.ArtistAnimation(fig, ims, interval=200, blit=True,repeat_delay=10000)
plt.show()

我从上面的代码得到的输出如下 code output

最佳答案

您需要在线条之后绘制更改后的艺术家(您的LineCollection)

col.set_array(colors)

您需要这样做,因为 LineCollection 首先添加到带有线的轴

ax.add_collection(col)

然后在循环中改变它。然后您必须更新图窗。最简单的方法是在该行之前调用 plt.draw()

im=ax.add_collection(col)

然而,这会重新绘制所有内容,并减慢动画的速度。解决方案是先在循环之前调用 plt.draw() 绘制所有其余部分,然后调用 ax.draw_artist(col)< 仅更新更改的艺术家。生成的代码如下所示

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()


ims=[]
plt.draw()
for i in range(100):
    col = LineCollection(lines,cmap=plt.cm.gray)
    colors = np.random.random(len(lines))
    col.set_array(colors)
    ax.draw_artist(col)
    im=ax.add_collection(col)
    ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=25, blit=True,repeat_delay=10000)
plt.show()

使用 FuncAnimation() 做同样的事情不那么棘手,参见示例 here ,但您说您出于某些原因不想使用它。

关于python - 循环更新帧时的 LineCollection 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20250154/

相关文章:

python - Flask Python - 将主机更改为 0.0.0.0 后,Put 请求仅返回 404

python - 带有 text.usetex 'true' 的轴字体不使用设置字体

Python matplotlib 叠加散点图

r - 如何在多层次分析中用不同颜色显示不同层次

python - 无法点击隐形选择python

python - 在 Keras 模型中加载时出现 TypeError

python - Seaborn 箱线图单个箱间距

python - 在绘图中显示 Y 轴网格线

r - 填写大纲

python - 计算 for 循环期间的运行总计 - Python