Live Matplotlib Graph in Tkinter Window in Python 3 – Tkinter tutorial Python 3.4 p. 7




[ad_1]

Tkinter GUI TutorialPlaylist: http://www.youtube.com/playlist?list=PLQVvvaa0QuDclKx-QpC9wntnURXVJqLyk

In this Tkinter tutorial, we take it a step further and show how we can have a live Matplotlib graph within our Tkinter GUI. How to put a matplotlib chart in a tkinter window has actually been one of the more popular requests that I’ve got, so I am happy to share this with you all finally!

http://seaofbtc.com
http://sentdex.com
http://hkinsley.com
https://twitter.com/sentdex

Bitcoin donations: 1GV7srgR4NJx4vrk7avCmmVQQrqmv87ty6

Source


[ad_2]

Comment List

  • sentdex
    December 12, 2020

    Thank you 🙂

  • sentdex
    December 12, 2020

    Sorry I got here 6 years late… but I'm having a problem… it says that x and y don't have the same dimesion :c

  • sentdex
    December 12, 2020

    Hi, Seems that I have an issue with your code with the lastest versions of Matplotlib (3.3.1) module 'matplotlib' has no attribute 'path'

  • sentdex
    December 12, 2020

    Thanks a lot, Sentdex! These tutorial videos have been very useful to me!

  • sentdex
    December 12, 2020

    hello sentdex
    I have written code for recording and playback the audio sound using GUI in python.
    now i want to create graph when I click play recorded sound so please help me

  • sentdex
    December 12, 2020

    Hey man, I'm taking an intro to python course where we build our own app, and I just couldn't get the hang of it for the life of me. I watched so many tutorial videos and nothing worked. But your videos are so helpful and easy to understand, I really appreciate that you take the time to talk in detail about how everything you type works. Your way of explaining code is so helpful, thank you so much, you're awesome.

  • sentdex
    December 12, 2020

    This helped me a lot, thanks. One question I still have is:

    "Why does animate() need to have a paramemer (i) that isn't even used?"

  • sentdex
    December 12, 2020

    I don't really understand the flow of the program. I'm coming from an embedded C background, where there's main(), with an infinite while loop. I guess this is run over and over?:
    app = SeaofBTCapp()

    ani = animation.FuncAnimation(f,animate, interval = 50) #interval is in milliseconds.

    app.mainloop()

    How can you add global functions to this program, and an infinite while loop?

  • sentdex
    December 12, 2020

    Hello,
    Can we connect the data results of a sensor6675 connected to an arduino and display the results as a real time graph using this ?
    Thank you

  • sentdex
    December 12, 2020

    J'ai rien compris… quelqu'un peut expliquer ? ou afficher le code ?

  • sentdex
    December 12, 2020

    thanks

  • sentdex
    December 12, 2020

    Great Videos

    How can I make all pages with animated plots? It's not working, only the last page remains animated always.
    Can you please tell about that? I didn't find it anywhere.

  • sentdex
    December 12, 2020

    Great videos! I have been using the matplotlib animation functions to display some real-time data. After running for a few hours I noticed the memory used by python kept creeping up and up. Do you face the same problem? Any suggestion?

  • sentdex
    December 12, 2020

    Hi, sentdex!
    These tutorials are very awesome to do. I am up to this video already, which says a lot, so thanks.

    One minor issue – this line is giving me trouble (maybe another like it, too):

    pullData = open("sampleData.txt", "r").read

    dataList = pullData.split('n')

    I get this error on load and an empty graph:


    File "first.py", line 22, in animate

    dataList = pullData.split('n')

    AttributeError: 'builtin_function_or_method' object has no attribute 'split'

    I have the latest Python, which is 3.7.2. I also have the latest matplotlib as well. What could I do to get my code to work like yours? T_T

  • sentdex
    December 12, 2020

    What if my 'x' is a date how would i append that or can you point me in the right direction?

  • sentdex
    December 12, 2020

    I have an entry box for the user to type something into, then a search button which uses the .get() function on the input from the user. ("tickerEntry.get()")
    How would I pass the value returned from .get() into the class for the next frame?
    Sorry if I explained that poorly ahah

  • sentdex
    December 12, 2020

    ValueError: x and y must have same first dimension, but have shapes (56,) and (0,)
    This error occurs when I try to run. Coming from x, y = self._xy_from_xy(x, y)
    Any idea why?

  • sentdex
    December 12, 2020

    I dont find the stylelib folder within my matplotlib package folder..please let me know…Thanks for the video

  • sentdex
    December 12, 2020

    Code to make fake data to feed your graph:

    import random

    data = ["1,8", "2,7", "3,5", "4,1", "5,3", "6,6","7,7", "8,5"]

    def getData():
    global data
    data2 = []
    data.pop(0)
    for d in data:
    d = d.split(",")
    d[0] = str(int(d[0]) -1)
    data2.append(d[0]+","+d[1])
    data2.append("8,"+random.choice(("1","2","3","4","5","6","7","8","9")))
    data=data2

    def animate(i):
    getData()
    xList, yList = [],[]
    for eachLine in data:
    if len(eachLine) > 1:
    x, y = eachLine.split(",")
    xList.append(int(x))
    yList.append(int(y))
    a.clear()
    a.plot(xList, yList)

  • sentdex
    December 12, 2020

    I need some serious help, I've detailed my exact issue here (https://stackoverflow.com/questions/51053091/creating-live-graphs-in-tkinter-which-require-parameters). What is really comes down to is that I need to give the animate function other parameters than just i, but when I do that, then it gives me a "None Type is not callable", which means that FuncAnimation isn't expecting parameters in the animate function.

  • sentdex
    December 12, 2020

    How do we add the drop down menu in this??

  • sentdex
    December 12, 2020

    I got a lot of errors. Where can I find the codes of this video?

  • sentdex
    December 12, 2020

    Hi Sentdex,

    If NavigationToolbar2TkAgg was depreciated in version 2.2, what should we use instead?

    I get this warning when running the code:

    Warning (from warnings module):
    File "/Users/newforolly/Documents/python/Robot/GUI.py", line 131
    toolbar = NavigationToolbar2TkAgg(canvas, self)
    MatplotlibDeprecationWarning: The NavigationToolbar2TkAgg class was deprecated in version 2.2.

    I'm on python 3.6.4
    MacOS 10.12.6
    program works as yours does but the toolbar is grey
    your videos are awesome

  • sentdex
    December 12, 2020

    Hi, Sentdex! Thanks for the video! It's the best!

    How can I include a "live entry" of data updates in the same way as done with the graph?

  • sentdex
    December 12, 2020

    I do not speak English, but I understand everything you say.

  • sentdex
    December 12, 2020

    thank you so much

  • sentdex
    December 12, 2020

    Hey Sentdex, The animation updating every 1s makes the window less responsive. I tried to thread the animation function but it gives a runtime error of 'dictionary changed size during iteration'. Any other way to make the window more responsive? BTW, Your videos are awesome and are really helpful

  • sentdex
    December 12, 2020

    why do I get this error ?

    AttributeError: 'NoneType' object has no attribute 'new_timer'

    using exact code

  • sentdex
    December 12, 2020

    Thanks for the awesome videos! I'm currently building a simple oscilloscope on a Pi and this helped make the GUI SO much nicer!

  • sentdex
    December 12, 2020

    #Code cheat cheat. As of December 2017. The BTC-e website was shut down. So i found my way using a different api. Try it out and provide feedback.

    import tkinter as tk
    from tkinter import ttk
    import matplotlib
    #from matplotlib.dviread import dpi
    from PIL.ImageOps import expand
    matplotlib.use("TKAgg")
    import matplotlib.animation as animation
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
    from matplotlib.figure import Figure
    from matplotlib import style
    import urllib
    import json
    import pandas as pd
    import numpy as np

    LARGE_FONT= ("Verdana", 12)
    style.use("ggplot")
    pd.options.mode.chained_assignment = None

    f= Figure(figsize=(5,5),dpi=100)
    a= f.add_subplot(111)

    def animate(i):
    dataLink='https://api.bitfinex.com/v1/trades/btcusd?limit=2000'
    data = urllib.request.urlopen(dataLink).read().decode("UTF-8")
    #data = data.readall().decode("utf-8")
    data=json.loads(data)
    data = pd.DataFrame(data)

    buys = data[(data['type'] =="buy")]
    buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
    buyDates =(buys["datestamp"]).tolist()

    sells = data[(data['type'] =="sell")]
    sells["datestamp"] = np.array(sells["timestamp"]).astype("datetime64[s]")
    sellDates =(sells["datestamp"]).tolist()

    a.clear()
    a.plot_date(buyDates, buys["price"],'-')
    a.plot_date(sellDates, sells["price"],'-')

    class SeaofBTCapp(tk.Tk):

    def __init__(self, *args, **kwargs):

    tk.Tk.__init__(self, *args, **kwargs)

    tk.Tk.iconbitmap(self, default="clienticon.ico")
    tk.Tk.wm_title(self, "Sea Of Bitcoin")
    container = tk.Frame(self)

    container.pack(side="top", fill="both", expand = True)

    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)

    self.frames = {}

    for F in (StartPage, PageOne, BTCE_HomePage):

    frame = F(container, self)

    self.frames[F] = frame

    frame.grid(row=0, column=0, sticky="nsew")

    self.show_frame(StartPage)

    def show_frame(self, cont):

    frame = self.frames[cont]
    frame.tkraise()

    class StartPage(tk.Frame):

    def __init__(self, parent, controller):
    tk.Frame.__init__(self,parent)
    label = tk.Label(self, text=("""ALPHA Bitcoin trading application
    use at your own risk.
    here is no promise of warranty."""), font=LARGE_FONT)
    label.pack(pady=10,padx=10)

    button1 = ttk.Button(self, text="Agree",
    command=lambda: controller.show_frame(BTCE_HomePage))
    button1.pack()

    button2 = ttk.Button(self, text="Disagree",
    command=quit)
    button2.pack()

    class PageOne(tk.Frame):

    def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
    label.pack(pady=10,padx=10)

    button1 = ttk.Button(self, text="Back to Home",
    command=lambda: controller.show_frame(StartPage))
    button1.pack()

    class BTCE_HomePage(tk.Frame):

    def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="Graph Page", font=LARGE_FONT)
    label.pack(pady=10,padx=10)

    button1 = ttk.Button(self, text="Back to Home",
    command=lambda: controller.show_frame(StartPage))
    button1.pack()

    canvas = FigureCanvasTkAgg(f,self)
    toolbar = NavigationToolbar2TkAgg(canvas,self)
    toolbar.update()
    canvas._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH,expand=True)

    canvas.show()
    canvas.get_tk_widget().pack(side=tk.TOP,fill=tk.BOTH,expand=True)

    app = SeaofBTCapp()
    ani = animation.FuncAnimation(f,animate, interval=1000)
    app.mainloop()

  • sentdex
    December 12, 2020

    Thank You!!

Write a comment