1

I want to update a single Matplotlib figure with each timestep in my Notebook. I have referenced numerous API resources and examples forum answers here on StackOverflow, however, all of the proposed code either did not graph or displayed a new figure with each timestep, like this answer,

import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np

# simulates input from serial port
def random_gen():
    while True:
        val = random.randint(1,10)
        yield val
        time.sleep(0.1)


a1 = deque([0]*100)
ax = plt.axes(xlim=(0, 20), ylim=(0, 10))
d = random_gen()

line, = plt.plot(a1)
plt.ion()
plt.ylim([0,10])
plt.show()

for i in range(0,20):
    a1.appendleft(next(d))
    datatoplot = a1.pop()
    line.set_ydata(a1)
    plt.draw()
    print a1[0]
    i += 1
    time.sleep(0.1)
    plt.pause(0.0001)                       #add this it will be OK.

and this answer.

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.1)

How can I update a figure with each timestep in Python, via Matplotlib or possibly other means? I appreciate your perspectives.

Thank you :)

1 Answers1

1

Real-time drawing by entering the interactive mode of matplotlib. If you only use plt.show() to draw, the program will stop executing the subsequent program, so open the drawing window through plt.ion() to enter the interactive mode, use the program plt.plot() to draw in real time, after the drawing is completed, use plt .ioff() exits the interactive mode and uses plt.show() to display the final image data. If plt.show() is not added at the end, it will flash back.

import matplotlib.pyplot as plt
import numpy as np

ax=[]  
ay=[]
bx=[]   
by=[]
num=0  
plt.ion()    
# plt.rcParams['savefig.dpi'] = 200 
# plt.rcParams['figure.dpi'] = 200 
plt.rcParams['figure.figsize'] = (10, 10)        
plt.rcParams['font.sans-serif']=['SimHei']   
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['lines.linewidth'] = 0.5   
while num<100:
    plt.clf()    
    plt.suptitle("TITLE",fontsize=30)            
    g1=np.random.random()  
    
    ax.append(num)      
    ay.append(g1)       
    agraphic=plt.subplot(2,1,1)
    agraphic.set_title('TABLE1')      
    agraphic.set_xlabel('x',fontsize=10)   
    agraphic.set_ylabel('y', fontsize=20)
    plt.plot(ax,ay,'g-')                
    #table2
    bx.append(num)
    by.append(g1)
    bgraghic=plt.subplot(2, 1, 2)
    bgraghic.set_title('TABLE2')
    bgraghic.plot(bx,by,'r^')

    plt.pause(0.4)     
    if num == 15:
        plt.savefig('picture.png', dpi=300) 
        #break
    num=num+1

plt.ioff()       
plt.show()       
HackerDev-Felix
  • 226
  • 2
  • 5
  • I copied and executed your code in my Notebook. The result generated 100 figures of TABLE1 and TABLE2, instead of 100 updates of the respective figures. This is presented in the "Brainstorming" cell of [this Notebook](https://github.com/freiburgermsu/dFBA/blob/main/2021-08-14_dFBA%20model_1.ipynb) in my Github repository. Is the error in my Notebook settings? Thank you :) – Freiburgermsu Sep 15 '21 at 04:15