3

I have written the following code with the help of online search. My intention here is to get a real time graph with time on x axis and some randomly generated value on y axis

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    xar = []
    yar = []
    x,y = time.time(), np.random.rand()
    xar.append(x)
    yar.append(y)
    ax1.clear()
    ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show() 

With the above code I just see the range of y axis changing continuously and the graph will not appear in the figure.

1 Answer 1

1

The problem is that you never update xvar and yvar. You can do that by moving the definitions of the lists outside the definition of animate.

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
xar = []
yar = []

def animate(i):
    x,y = time.time(), np.random.rand()
    xar.append(x)
    yar.append(y)
    ax1.clear()
    ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.