简体   繁体   English

在散点 plot 上绘制 matplotlib.animation 中的垂直线

[英]Plotting vertical lines in matplotlib.animation over a scatter plot

I am wanting to use matplotlib.annimation to sequentially plot data points and plot vertical lines as they become known.我想使用matplotlib.annimation顺序 plot 数据点和 plot 垂直线,因为它们变得已知。

What I have at the moment is the following:我目前拥有的是以下内容:

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

I would like to plot vertical lines outputted from a function as described in the comments in the animate function.我想 plot 从 function 输出的垂直线,如动画 function 中的评论中所述。

The lines are subject to change as more data points are processed.随着更多数据点的处理,线条可能会发生变化。

I wrote the code with the understanding that I wanted to draw a vertical line along the index of the line graph.我写代码的理解是我想沿着折线图的索引画一条垂直线。 I decided on the length and color of the vertical line, and wrote the code in OOP style, because if it is not written in ax format, two graphs will be output.我决定了竖线的长度和颜色,把代码写成OOP的样式,因为如果不写成ax格式,两个图就是output。

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM