1

I want to update subplots that are embedded into a Canvas in a tkinter GUI. Whatsoever I try, my intention fails. See how far I am:

from tkinter import *
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
import matplotlib.pyplot as plt
import time
root = Tk()
figId = plt.figure()
canvas = FigureCanvasTkAgg(figId, master=root)
canvas.get_tk_widget().pack()
canvas.draw()
vals1 = [5, 6, 3, 9]
vals2 = vals1
for i in range(0, len(vals1)+1):
 toPlot = vals1[0:i]
 plt.subplot(211).plot(toPlot)
 plt.subplot(212).plot(toPlot)
 time.sleep(1)
root.mainloop()

I figured out that doing something like plt.pause(.1) is not the right way. For me, it seems that I have to introduce matplotlib.animation, but I really have no clue how to do that.

martineau
124k29 gold badges180 silver badges317 bronze badges
asked Oct 26, 2020 at 13:17

1 Answer 1

1

I found the answer:

import random
from itertools import count
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from tkinter import *
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
x_vals = []
y_vals1 = []
y_vals2 = []
index = count()
root = Tk()
figId = plt.figure()
canvas = FigureCanvasTkAgg(figId, master=root)
canvas.get_tk_widget().pack()
canvas.draw()
def animate(i):
 x_vals.append(next(index))
 y_vals1.append(random.randint(0, 5))
 y_vals2.append(random.randint(0, 5))
 plt.cla()
 plt.plot(x_vals, y_vals1)
 plt.plot(x_vals, y_vals2)
ani = FuncAnimation(plt.gcf(), animate, interval=1000)
root.mainloop()
answered Oct 26, 2020 at 14:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.