gpt4 book ai didi

python - 用不同的颜色为一条线设置动画

转载 作者:太空宇宙 更新时间:2023-11-03 15:15:51 25 4
gpt4 key购买 nike

我正在尝试为演示文稿制作我的数据动画。我正在尝试使用 python 的动画包来这样做。我想做的事情大致归结为 http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ 中的第一个例子。

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

我是 python 的新手,所以我很难理解正在发生的事情。对我来说,似乎 init() 和 animate(i) 都没有修改它们返回的内容。此外,他们正在修改的对象 line(而不是 line)之前并未声明。

无论哪种方式,我想要做的是让数据(在本例中为正弦波)分段着色。蓝色介于 0 和 1 之间,红色介于 1 和 1.5 之间,蓝色又介于 1.5 和 2 之间。我尝试了很多东西,但无法让它发挥作用。我尝试让这些函数返回整个图形,而不仅仅是线条,希望它们能刷新预览图形并绘制我绘制的复合线,但无济于事。

在此框架中,我如何为由(不同颜色的)线段组成的线设置动画?

最佳答案

要绘制一条属性沿其变化的线,请使用 LineCollection。示例 herehere .要使用 LineCollection 制作动画,请参阅 this示例。

为了回答上面代码中的事情是如何工作的,在 animate() 中,您正在使用 line.set_data(x , y)。该函数然后将 matplotlib 必须在每一帧更新的艺术家集合 (line,) 返回给 Matplotlib。

这就是我认为您正在寻找的内容(仅当您的平台在上次调用中支持它时才启用 blit=true):

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

cmap = ListedColormap(['b', 'r', 'b'])
norm = BoundaryNorm([0, 1, 1.5, 2], cmap.N)

line = LineCollection([], cmap=cmap, norm=norm,lw=2)
line.set_array(np.linspace(0, 2, 1000))
ax.add_collection(line)

# initialization function: plot the background of each frame
def init():
line.set_segments([])
return line,

# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
line.set_segments(segments)
return line,

# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20)

enter image description here

关于python - 用不同的颜色为一条线设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21077477/

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