аватар question@mail.ru · 01.01.1970 03:00

Как анимировать график?

Подскажите есть ли возможность в jupyter рисовать анимированные графики, вроде графика загрузки процессора в реальном времени? Пытаюсь сделать мониторинг времени ответа сервера на пинг. Разбираюсь с matplotlib, но то ли он такого не умеет, то ли я не нашел:

import subprocessimport refrom matplotlib import pyplot as pltdef ping(adress):    p = subprocess.Popen([""ping.exe"",adress], stdout = subprocess.PIPE)    out = p.communicate()[0]    t = re.search(r'time=(\d*)',str(out))    time = t.group().replace('time=','') if t else '0'    retu (time)x=[0]%matplotlib inlinefor i in range(0,10):    x.append(ping('ya.ru'))    plt.plot(x)

График просчитывается весь и отрисовывается весь сразу. Подскажите, как сделать анимацию и возможно ли вообще такое?

аватар answer@mail.ru · 01.01.1970 03:00

Можно так сделать:

import psutilfrom datetime import datetime as dtfrom collections import dequeimport matplotlib.pyplot as pltfrom matplotlib.dates import date2numimport matplotlib.animation as animation%matplotlib notebookN=600x = deque([date2num(dt.now())], maxlen=N)y = deque([0], maxlen=N)fig, ax = plt.subplots(figsize=(8,3))line, = ax.plot_date(x, y, marker="""")ax.spines['left'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)def get_data():    # retu ping('ya.ru')    retu psutil.cpu_percent(.15)def animate(i):    x.append(date2num(dt.now()))    y.append(get_data())    ax.relim(visible_only=True)    ax.autoscale_view(True)    line.set_data(x, y)    ax.fill_between(x, -0.5, y, color='lightgrey')    retu line,ani = animation.FuncAnimation(fig, animate, interval=300)#ani.save(""d:/temp/test.gif"", writer='imagemagick', fps=10)plt.show()

Результат:

Последние

Похожие