Dynamic permutation

I need to build many lines, and I would like to show them as they are calculated. The code looks something like this:

x = arange(100000)
for y in range(100000):
    ax.plot(x*y)
    draw()

Now, as you can imagine, this happens very quickly. What I thought I could do was plot, save the plot to the buffer, clear the plot, lay the buffer as the background, and then build the next line. Thus, I do not get so many Line2D objects. Does anyone have any ideas?

+4
source share
2 answers

It seems you need the matplotlib.animation function. animation examples .

EDIT: Added a simple code example of my version.

import random
from matplotlib import pyplot as plt
from matplotlib import animation

def data_generator(t):
    if t<100:
        return random.sample(range(100), 20)

def init():
    return plt.plot()

def animate(i):
    data = data_generator(i)
    return plt.plot(data, c='k')

fig = plt.figure()
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=1000, interval=1000, blit=True)
plt.show()

EDIT2: multi-line version in real time.

import random
from matplotlib import pyplot as plt
from matplotlib import animation

def data_generator_1(t):
    if t<100:
        x1.append(t)
        y1.append(random.randint(1, 100))

def data_generator_2(t):
    if t<100:
        x2.append(t)
        y2.append(random.randint(1, 100))

def init():
    global x1
    global y1
    x1 = []
    y1 = []

    global x2
    global y2
    x2 = []
    y2 = []

    l1, l2 = plt.plot(x1, y1, x2, y2)
    return l1, l2

def animate(i):
    data_generator_1(i)
    data_generator_2(i)
    l1, l2 = plt.plot(x1, y1, x2, y2)
    plt.setp(l1, ls='--', c='k')
    plt.setp(l2, c='gray')
    return l1, l2

fig = plt.figure()
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=1000, interval=1000, blit=True)
plt.show()

enter image description here

, . , , .

ipython/vanilla, . ( ipython). , matplotlib.

+4

, ipython, IPython:

from IPython import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib

x = np.arange(100)

for y in np.arange(100):  
    fig, ax = plt.subplots(1,1, figsize=(6,6))
    ax.plot(x * y)
    ax.set_ylim(0, 10000) # to keep the axes always the same
    display.clear_output(wait=True)
    display.display(fig)
    plt.close()

, 10 , :

x = np.arange(100)
fig, ax = plt.subplots(1,1, figsize=(6,6))
for y in np.arange(100):        
    ax.plot(x*y)
    ax.set_ylim(0,10000)
    display.clear_output(wait=True)
    display.display(fig)
    if y > 10:           # from the 10th iteration,
        ax.lines.pop(0)  # remove the first line, then the 2nd, etc.. 
                         # but it will always be in position `0`
plt.close()

0

Source: https://habr.com/ru/post/1599002/


All Articles