I'm new to Python matplotlib
and want to make a figure updated in a loop.
This is some simple test code. I want to draw 3 graphs, each for 2 seconds, with different slopes each time. Of course, I know I should read some more about matplotlib
but I need to do something quick. What is wrong below? Thanks!
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import time
def demo(a):
y = [xt*a+1 for xt in x]
ax.plot(x,y)
if __name__ == '__main__':
plt.ion()
fig, ax = plt.subplots()
ax.set_ylim([0,15])
x = range(0,5)
for a in range(1,4):
demo(a)
time.sleep(2)
I thought plt.ion()
makes it interactive and ax.plot(x,y)
take effect instantly (but guess not). I tried adding ax.draw()
after ax.plot(x,y)
but it requires some arguments like artist or something which I don't know yet :). Also, I have this error message coming (Ubuntu 14.04.LTS).
Xlib: extension "XInputExtension" missing on display ":1.0".
X Error: BadDrawable (invalid Pixmap or Window parameter) 9
Major opcode: 62 (X_CopyArea)
Resource id: 0x0
EDIT : I add the correct code below. (according to Estilus's solution to which I modified a little for correct graph display.
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import time
def demo(a):
plt.cla()
y = [xt*a+1 for xt in x]
ax.set_ylim([0,15])
ax.plot(x,y)
if __name__ == '__main__':
plt.ion()
fig, ax = plt.subplots()
x = range(5)
for a in range(1,4):
demo(a)
plt.pause(3)
plt.draw()