簡體   English   中英

在散點 plot 上繪制 matplotlib.animation 中的垂直線

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

我想使用matplotlib.annimation順序 plot 數據點和 plot 垂直線,因為它們變得已知。

我目前擁有的是以下內容:

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

我想 plot 從 function 輸出的垂直線,如動畫 function 中的評論中所述。

隨着更多數據點的處理,線條可能會發生變化。

我寫代碼的理解是我想沿着折線圖的索引畫一條垂直線。 我決定了豎線的長度和顏色,把代碼寫成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