设置不同颜色的线动画

发布于 2021-01-29 16:18:01

我正在尝试为演示制作数据动画。我正在尝试使用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)都不会修改它们返回的内容。而且,他们正在修改的对象,行(而不是行)以前没有声明过。

无论哪种方式,我都想做的是获取数据,在这种情况下为正弦波,逐段着色。蓝色介于0和1之间,蓝色介于1和1.5之间,蓝色再次介于1.5和2之间。我已经尝试了很多方法,但是无法使其正常工作。我尝试使用这些函数返回整个图形,而不仅仅是返回行,希望它们刷新预览图形并绘制我绘制的复合线,但无济于事。

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

关注者
0
被浏览
49
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    要绘制其属性沿其变化的线,请使用LineCollection。这里这里的例子。要使用LineCollection制作动画,请参见以下示例。

    要回答上面代码中的内容,animate()请在其中使用重置行x,y属性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)
    

    在此处输入图片说明



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看