【问题标题】:Plotting vertical lines in matplotlib.animation over a scatter plot在散点图上绘制 matplotlib.animation 中的垂直线
【发布时间】:2021-05-07 13:55:27
【问题描述】:

我想使用matplotlib.annimation 顺序绘制数据点并绘制已知的垂直线。

我目前拥有的如下:

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

x = np.arange(len(data))
y = data


fig = plt.figure()
plt.xlim(0, len(data))
plt.ylim(-8, 8)
graph, = plt.plot([], [], 'o')

def animate(i):
    # line_indicies = func(x[:i+1])
    graph.set_data(x[:i+1], y[:i+1])
    # then I would like something like axvline to plot a vertical line at the indices in line indices 

    return graph

anim = FuncAnimation(fig, animate, frames=100, interval=200)
# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()

我想绘制从 animate 函数中的 cmets 中描述的函数输出的垂直线。

随着处理更多数据点,线条可能会发生变化。

【问题讨论】:

    标签: python matplotlib matplotlib-animation


    【解决方案1】:

    我写代码的理解是我想沿着折线图的索引画一条垂直线。我决定了竖线的长度和颜色,代码是OOP风格的,因为如果不写成ax格式,会输出两张图。

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    data = np.random.randint(-8,8,(100,))
    x = np.arange(len(data))
    y = data
    
    fig = plt.figure()
    ax = plt.axes(xlim=(0, len(data)), ylim=(-8, 8))
    graph, = ax.plot([], [], 'o')
    lines, = ax.plot([],[], 'r-', lw=2)
    
    def init(): 
        lines.set_data([],[])
        return 
    
    def animate(i):
        graph.set_data(x[:i+1], y[:i+1])
        # ax.axvline(x=i, ymin=0.3, ymax=0.6, color='r', lw=2)
        lines.set_data([i, i],[-3, 2])
        return graph
    
    anim = FuncAnimation(fig, animate, frames=100, interval=200)
    # anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
    plt.show()
    

    【讨论】:

    • 感谢您的回答。有一个小问题。随着处理更多点,线条可能会发生变化,当我对其进行测试时,如果我不希望它们被绘制,之前的线条仍然存在。
    • 为了避免留下线条,我们将 axvline 改为普通绘图,并引入了一个初始化函数来修改线条,以便在每次动画后对其进行初始化。