matplotlib update figure in loop [duplicate]

Вы можете использовать эту пользовательскую библиотеку (написанную с помощью Promise) для выполнения удаленного вызова.

function $http(apiConfig) {
    return new Promise(function (resolve, reject) {
        var client = new XMLHttpRequest();
        client.open(apiConfig.method, apiConfig.url);
        client.send();
        client.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                // Performs the function "resolve" when this.status is equal to 2xx.
                // Your logic here.
                resolve(this.response);
            }
            else {
                // Performs the function "reject" when this.status is different than 2xx.
                reject(this.statusText);
            }
        };
        client.onerror = function () {
            reject(this.statusText);
        };
    });
}

Пример простого использования:

$http({
    method: 'get',
    url: 'google.com'
}).then(function(response) {
    console.log(response);
}, function(error) {
    console.log(error)
});
96
задан nbro 4 May 2015 в 22:34
поделиться

6 ответов

У вас по существу есть две возможности:

  1. Сделайте именно то, что вы сейчас делаете, но назовите graph1.clear() и graph2.clear() перед тем, как выполнить повторную передачу данных. Это самый медленный, но самый простой и наиболее надежный вариант.
  2. Вместо ретрансляции вы можете просто обновить данные объектов сюжета. Вам нужно будет внести некоторые изменения в свой код, но это должно быть намного быстрее, чем при каждом повторном использовании. Однако форма данных, которые вы рисуете, не может измениться, и если диапазон ваших данных меняется, вам необходимо вручную сбросить пределы оси x и y.

Чтобы привести пример второй опции:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)

# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

for phase in np.linspace(0, 10*np.pi, 500):
    line1.set_ydata(np.sin(x + phase))
    fig.canvas.draw()
    fig.canvas.flush_events()
108
ответ дан gbmhunter 27 August 2018 в 23:11
поделиться

Вы также можете сделать следующее: это приведет к отображению случайных матричных данных 10x1 на графике для 50 циклов цикла for.

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()
4
ответ дан Arindam 27 August 2018 в 23:11
поделиться

Я выпустил пакет под названием python-drawow , который предоставляет функциональные возможности, позволяющие обновлять фигуры, обычно вызываемые в цикле for, подобно Matlab's drawnow.

An пример использования:

from pylab import figure, plot, ion, linspace, arange, sin, pi
def draw_fig():
    # can be arbitrarily complex; just to draw a figure
    #figure() # don't call!
    plot(t, x)
    #show() # don't call!

N = 1e3
figure() # call here instead!
ion()    # enable interactivity
t = linspace(0, 2*pi, num=N)
for i in arange(100):
    x = sin(2 * pi * i**2 * t / 100.0)
    drawnow(draw_fig)

Этот пакет работает с любым рисунком matplotlib и предоставляет опции для ожидания после обновления каждой цифры или перехода в отладчик.

8
ответ дан Community 27 August 2018 в 23:11
поделиться
import csv
import sys
import getopt
import socket
import time
import numpy as np
import matplotlib
from scipy.misc import imread
from matplotlib import pyplot as plt
import warnings
fig, ax = plt.subplots()
ax.set_xlim(-158, 553)
ax.set_ylim(-290, 733)
im = plt.imread("")
plt.imshow(img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])

fig.show()
l_global=[]
points=[]
master_tag_csvlink='c:/logfolde.log.csv'
csvfile=open(master_tag_csvlink, 'r')
for ainfo in csvfile:
        line= ainfo
        l_list= list(line.split('_'))
        l_local=[]
        for i in range(int(l_list[0])):
            l_local.append(list(l_list[i+1].split(',')))
        function1= lambda x,i: x[i] # return list[n,X] of elements at x
        c= lambda x,l: [x for i in range(l) if True]
        for i in range(len(l_local)):
            l_local[i][1],l_local[i][2]=int(l_local[i][1]),int(l_local[i][2])

        if l_global: #In begining l_glocal is empty, so just copy the data in to l_global
            l_global=l_local[:]
            for i in range(len(l_global)):
                points.append(plt.plot(function1(l_global[i],1),function1(l_global[i],2),'g',label="Tag:%s, X:%f, y: %f"%(function1(l_global[i],0),function1(l_global[i],1),function1(l_global[i],2))))



        else: # compare the l_local & l_global for any updates 
            tag_Id=map(function1,l_local,c(0,len(l_local))) #list of list of tagId,x,y TagId is filtered - local
            mTag_Id=map(fuction1,l_global,c(0,len(l_global))) #list of list of tagId,x,y TagId is filtered - master

            for i in mTag_Id: 
                if i not in tag_Id: #comparing master tags and tag_Id's
                    index=mTag_Id.index(i) ###############  Tags in master list but not in Tag_id
                    copy_point=l_global[index]
                    [removing_point]=points[index]########  means tag is in-active ,turn tag color into red
                    removing_point.remove()
                    del points[index]

                    points.insert(index,plt.plot(function1(l_global[index],1),function1(l_global[index],2),'r',label="Tag:%s, X:%f, y: %f"%(function1(l_global[i],0),function1(l_global[i],1),function1(l_global[i],2))))

                elif i in tag_Id: # append the tag into l_global
                    index=mTag_Id.index(i) ###############  Tags in master list but not in Tag_id
                    l_global[index]=l_local[index][:]
                    [removing_point]=points[index]########  means tag is active update coordinates
                    removing_point.remove()
                    del points[index]
                    points.insert(index,plt.plot(function1(l_global[index],1),function1(l_global[index],2),'g',label="Tag:%s, X:%f, y: %f"%(function1(l_global[i],0),function1(l_global[i],1),function1(l_global[i],2))))
            for i in Tag_Id:
                if i not in mTag_Id:
                    index=Tag_Id(i)
                    l_global.append(l_local[index]]
                    points.append(plt.plot(function1(l_global[-1],1),function1(l_global[-1],2),'g',label="Tag:%s, X:%f, y: %f"%(function1(l_global[i],0),function1(l_global[i],1),function1(l_global[i],2))))

# import matplotlib.pyplot as plt
# import numpy as np

# x = np.linspace(0, 6*np.pi, 100)
# y = np.sin(x)

# # You probably won't need this if you're embedding things in a tkinter plot...
# plt.ion()

# fig = plt.figure()
# ax = fig.add_subplot(11)1
# line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

# for phase in np.linspace(0, 10*np.pi, 500):
    # line1.set_ydata(np.sin(x + phase))
    # fig.canvas.draw()
-2
ответ дан DILEEP_B 27 August 2018 в 23:11
поделиться

Все вышеизложенное может быть правдой, однако для меня «онлайн-обновление» цифр работает только с некоторыми бэкэндами, в частности wx. Вы просто можете попытаться изменить это, например. путем запуска ipython / pylab ipython --pylab=wx! Удачи!

3
ответ дан jkeyser 27 August 2018 в 23:11
поделиться

Это сработало для меня. Неоднократно вызывает функцию, обновляющую график каждый раз.

import matplotlib.pyplot as plt
import matplotlib.animation as anim

def plot_cont(fun, xmax):
    y = []
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)

    def update(i):
        yi = fun()
        y.append(yi)
        x = range(len(y))
        ax.clear()
        ax.plot(x, y)
        print i, ': ', yi

    a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
    plt.show()

«fun» - это функция, которая возвращает целое число. FuncAnimation будет многократно называть «обновление», он будет делать это «xmax» раз.

12
ответ дан Vituel 27 August 2018 в 23:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: