0

I would like to know how to update a graph and or plot in matplotlib every few seconds. Code:

import matplotlib.pyplot as plt
import numpy as np
axes = plt.gca()
axes.set_xlim([0,5])
axes.set_ylim([0,100])
X = [0, 1, 2, 3, 4, 5]
Y = [15, 30, 45, 60, 75, 90]
plt.plot(X, Y)
plt.xlabel('Time spent studying (hours)')
plt.ylabel('Score (percentage)')
plt.show()
Qwertykey
  • 21
  • 5

2 Answers2

0

What you have written is correct , but in order to make your code dynamic , you can put the code in a function and pass the X and Y coordinates to the function . One example as shown below

def GrapgPlot(X, Y):


   "Your code"
GrapgPlot([0, 1, 2, 3, 4, 5],[90, 30, 45, 60, 75, 90])

In the plot if you are certain that X axis will not change than you can fix X axis in the code and take only Y axis values as a list from the user as an input and pass it in the function as an argument.

else the best way if you do want user interaction . Update the X and Y axis list with a loop and pass X and Y values in the function as an argument

Ankan Roy
  • 17
  • 6
0

Used time.sleep(1) for being able to see the changes and reversed Y for new data to be updated. Hopefully this is what you want:

%matplotlib notebook

import time

import matplotlib.pyplot as plt

X = [0, 1, 2, 3, 4, 5]
Y = [15, 30, 45, 60, 75, 90]

fig, ax = plt.subplots()
ax.set_xlim([0,5])
ax.set_ylim([0,100])
ax.set_xlabel('Time spent studying (hours)')
ax.set_ylabel('Score (percentage)')
l, = ax.plot(X, Y)

for ydata in [Y, Y[::-1]]*2:
    l.set_ydata(ydata)
    fig.canvas.draw()
    time.sleep(0.5)
Y. Luo
  • 5,622
  • 1
  • 18
  • 25