gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:30:45 24 4
gpt4 key购买 nike

我有一个由大量线条组成的情节。在每一步,线条的颜色都应该在动画中更新,但是在线条上做一个 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()

而且我无法与动画艺术家合作!我用的是画图。动画台词有什么问题

现在将这些 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()

正如我所说,我想将它与动画并排运行。所以我更喜欢把它做成动画。我认为这至少会在动画开始后解决滞后问题,但现在按照我定义的方式,它不起作用。

最佳答案

为此使用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()

enter image description here

关于python - 仅基于更新图中颜色的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20053964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com