live plot

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

live plot

Rached Zakhama

Hi,

I was trying to make a live plot with tkinter where I can see the data updating live in a for loop. I used a tkinter window to plot the matplotlib figure and I added a button. The problem is that I can't make the button work during the for loop.

My example is :

##############################

# imports

import numpy as np
from time import sleep
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib.pyplot import pause
import tkinter as tk

fenetre = tk.Tk()
# update function , called whenever the user hit the button : changes the plot line color
def update():
    n=np.random.randint(4)
    colors=['b','g','r','c']
    l.set_color(colors[n])
    canvas.show()
# tkinter button, changes the line color
bouton = tk.Button(fenetre, text="change color", command=update)
bouton.pack()
# create random data
x=np.array([i for i in range(10)])
y=np.random.randn(10)
# create matplotlib figure and plot
fig=Figure(figsize=(5,5))  
ax=fig.add_subplot(111)
l,=ax.plot(x,y)
# put the figure in the tkinter window
canvas=FigureCanvasTkAgg(fig,fenetre)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP,fill=tk.BOTH, expand=True)
# add the toolbar
toolbar= NavigationToolbar2TkAgg(canvas,fenetre)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH, expand=True)

# update random data every  2 seconds
for i in range(15):
    sleep(2)
    y=np.random.randn(10)
    l.set_ydata(y)
    canvas.show()


tk.mainloop()

######################

I am trying to see a plot random data changing on the screen every 2 seconds and change its color whenever I hit the button. It doesn't work since apparently Python  doesn't execute the button  command before finishing the loop.

Do you have any suggestions.

Waiting hopefully for your replay.

Best regards.

___________________________________________________________________
Rached ZAKHAMA
Bureau 2B1 33
Thales Research & Technology
III-V lab, 91120 Palaiseau,France

tel: <a href="callto:+33%280%29169416021" target="_blank">+33(0)169416021   +33(0)658787715
___________________________________________________________________
_______________________________________________
Matplotlib-users mailing list
[hidden email]
https://mail.python.org/mailman/listinfo/matplotlib-users