how to plot results in real time
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
method 1: clear axes before plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for i in range(20):
x = np.arange(0, i, 0.1);
y = np.sin(x)
ax.set_xlim(0, i)
ax.cla()
ax.plot(x, y)
display(fig)
clear_output(wait = True)
plt.pause(0.5)
method 2: set fixed x range and don't clear axes every step
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for i in range(21):
ax.set_xlim(0, 20)
ax.set_ylim(-1.2, 1.2)
ax.plot(i, np.sin(i),marker='x')
display(fig)
clear_output(wait = True)
plt.pause(0.5)
clear_output(wait=True) will erase the current contents when the next content is displayed, so don't print anything after plotting!
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for i in range(10):
x = np.arange(0, i, 0.1);
y = np.sin(x)
ax.set_xlim(0, i)
ax.cla()
ax.plot(x, y)
display(fig)
clear_output(wait = True)
plt.pause(0.5)
print("This message will erase the figure, be careful")
This message will erase the figure, be careful