Matplot/Pandas X-axis is not showing for all the values - python

I ran this program. For some reason I am not getting all the X-axis values. Tried to change the data still no printing.
import matplotlib.pyplot as plt
import pandas as pd
import tkinter as tk
import pandas as pd
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from pandas import Timestamp
import sys
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
root = Tk.Tk()
top = Tk.Frame(root)
top.pack()
bottom = Tk.Frame(root)
bottom.pack()
fig = plt.Figure()
canvas = FigureCanvasTkAgg(fig, top)
canvas.get_tk_widget().pack()
canvas._tkcanvas.pack()
df = pd.read_csv("../data.csv")
ax = fig.add_subplot(111)
fig.suptitle('App Server CPU%', fontsize=12)
df['date'] = pd.to_datetime(df['date'], format='%Y/%m/%d %H:%M:%S')
df = df.set_index('date')
grouped = df.groupby(['server'])
for key, group in grouped:
group['utilization'].plot(label=key, ax=ax)
plt.legend(loc='best')
def on_closing():
#if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.lift()
root.attributes('-topmost',True)
root.mainloop()
date,server,utilization
2004-08-19,App1,105.01
2004-08-20,App1,106.06
2004-08-23,App1,116.3
2004-08-24,App1,116.8
2004-08-25,App1,110
2004-08-26,App1,110.2
2004-08-27,App1,113.51
2004-08-19,App2,126.01
2004-08-20,App2,127.27
2004-08-23,App2,139.56
2004-08-24,App2,140.16
2004-08-25,App2,132
2004-08-26,App2,132.24
2004-08-27,App2,136.21
2004-08-19,App3,157.52
2004-08-20,App3,159.09
2004-08-23,App3,174.45
2004-08-24,App3,175.2
2004-08-25,App3,165
2004-08-26,App3,165.3
2004-08-27,App3,170.26

Related

Im trying to add a matplotlib chart on a Tkinter GUI... Can someone help me?

I have this code here where I am trying to import a seaborn ecdf plot on a Tkinter GUI but it is not working. The plot just doesnt pop up when I run the program. Ultimatly, I would like to make the plot updating with real-time data. Is it possible and if yes, how would I go about doing this. Thank you for your time.
from tkinter import *
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
from data import GetData
"""Initiate Root"""
Root = Tk()
Root.title('Profondeur du marché')
Root.iconphoto(False, PhotoImage(file = 'Logo.png'))
Root.configure(background = '#2E2D2B')
Root.geometry('1000x800')
"""Define df"""
df = GetData()
"""Create Plot"""
fig, ax = plt.subplots()
ax.set_title('Le livre de liquidité du Bitcoin en temps réel')
"""Bids"""
BidsPlot = sns.ecdfplot(x="Price",
weights="Volume",
stat="count",
complementary=True,
data=df.query("Side == 'bids'"),
color="green",
ax=ax)
"""Asks"""
AsksPlot = sns.ecdfplot(x="Price",
weights="Volume",
stat="count",
data=df.query("Side == 'asks'"),
color="red",
ax=ax)
"""Set axes titles"""
ax.set_xlabel('Prix')
ax.set_ylabel('Volume')
"""Initiate Canvas"""
Canvas = FigureCanvasTkAgg(fig,
master = Root)
Canvas.draw()
Root.mainloop()

How to update matplotlib subplots on a tkinter Canvas?

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.
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()

Animate Matplotlib graph inside Toplevel in Tkinter

I'm new to tkinter, so if there's anything very wrong, I'm sorry. That said...
I'm using python 3.
The title is pretty self-explanatory. I'm trying to animate a graph inside my tk.Toplevel in my application. I've deleted all remaining code to simplify the question. This code doesn't work even if I put animation.FuncAnimation just before root.mainloop().
Here's my code:
import tkinter as tk
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.animation as animation
def running():
#Animate the graph
def animate(i):
global df1
df1 = pd.concat([df1,pd.DataFrame({'Country':[None],'GDP_Per_Capita':[df1['GDP_Per_Capita'].iloc[-1]+10]})],sort=False)
ax1.clear()
ax1.hist(df1['GDP_Per_Capita'], len(df1), density=1, histtype='step',
cumulative=True, label='Empirical')
global df1
t = tk.Toplevel()
t.wm_title("Running")
figure1 = plt.Figure(figsize=(6,5), dpi=100)
ax1 = figure1.add_subplot(111)
bar1 = FigureCanvasTkAgg(figure1, t)
bar1.get_tk_widget().grid(column=0,row=0,columnspan=2)
n, bins, patches = ax1.hist(df1['GDP_Per_Capita'], 5, density=1, histtype='step',
cumulative=True, label='Empirical')
ax1.set_title('Country Vs. GDP Per Capita')
ani = animation.FuncAnimation(figure1, animate, interval=1000)
if __name__ == "__main__":
root = tk.Tk()
root.title("Testing")
#Sample Data
Data1 = {'Country': ['US','CA','GER','UK','FR'],
'GDP_Per_Capita': [10,15,25,45,50]
}
df1 = pd.DataFrame(Data1, columns= ['Country', 'GDP_Per_Capita'])
df1 = df1[['Country', 'GDP_Per_Capita']].groupby('Country').sum()
tk.Button(root,
text='START', command=running, width=9, height=2, activebackground="white", bg="#006d88",bd=4).grid(row=0, column=1, sticky="E",padx=(0,10))
root.mainloop()
This question is not the same as this Python Tkinter Animation since I'm running the animation inside Toplevel. If I was running in root, it would work.

How can I update a heatmap on a GUI when I change the input values

I am trying to display a GUI with a heatmap and scales/sliders with the scales/sliders changing the values in the heatmap.
I can display the heatmap and sliders and can read from the sliders but I cannot get the heat map to update after I have moved the sliders.
I have tried putting the code (I think) updates the heatmap in a function which is called whenever the scale/slider is moved but I am clearly missing something.
import tkinter
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def myFunc(value):
print (mySlider.get())
array[1][2]=mySlider.get()
#I think I need to put something here to update the heatmap when the
#scale/slider is changed but do not know what
figure, ax = plt.subplots()
ax.imshow(array)
canvas.get_tk_widget().pack()
root = tkinter.Tk()
root.title("Something")
array = ([[1,2,3,4],
[3,9,1,5],
[8,4,1,7],
[2,4,9,1]])
figure, ax = plt.subplots()
ax.imshow(array)
canvas = plt.Figure()
canvas = FigureCanvasTkAgg(figure, root)
canvas.get_tk_widget().pack()
mySlider = tkinter.Scale(root, from_=0, to=15, orient=HORIZONTAL, command=myFunc)
mySlider.pack()
Like this:
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def myFunc(value):
print (mySlider.get())
array[1][2]=mySlider.get()
im.set_array(array)
canvas.draw()
root = tk.Tk()
root.title("Something")
array = ([[1,2,3,4],
[3,9,1,5],
[8,4,1,7],
[2,4,9,1]])
figure, ax = plt.subplots()
im = ax.imshow(array)
canvas = FigureCanvasTkAgg(figure, root)
canvas.get_tk_widget().pack()
mySlider = tk.Scale(root, from_=0, to=15, orient=tk.HORIZONTAL, command=myFunc)
mySlider.pack()
root.mainloop()
However tkinter is not needed here. matplotlib has a slider built in (I assume you know since you imported it) which is a lot easier to implement:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
def myFunc(value):
array[1][2]=value
im.set_array(array)
array = ([[1,2,3,4],
[3,9,1,5],
[8,4,1,7],
[2,4,9,1]])
figure, ax = plt.subplots()
im = ax.imshow(array)
ax_slider = plt.axes([0.1, 0.1, 0.8, 0.03]) # [left, bottom, width, height]
slide = Slider(ax_slider, '', 0, 15, valinit=0)
slide.on_changed(myFunc)
plt.show()

Graphs in Canvas

I am trying to show up the line graphs (Strings and Numbers )as shown in the array) in a Canvas. I got this code from different questions in this forums, trying to modify for my requirements.Can some one please guide me.
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"Week": ['Week1','Week2','Week3','Week4','Week5'],
"App1" : [2.6,3.4,3.25,2.8,1.75],
"App2" : [2.5,2.9,3.0,3.3,3.4],
"App3" : [1.6,2.4,1.25,5.8,6.75]})
df.plot(x="Week", y=["App1", "App2", "App3"])
plt.show()
Here is the one, in case if someone else is looking.
# --- matplotlib ---
import matplotlib
matplotlib.use('TkAgg') # choose backend
from tkinter import messagebox
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
NavigationToolbar2TkAgg
from matplotlib.pyplot import Figure
from matplotlib import pyplot as plt
# --- other ---
import tkinter as tk
import pandas as pd
# --- GUI ---
root = tk.Tk()
# top frame for canvas and toolbar - which need `pack()` layout manager
top = tk.Frame(root)
top.pack()
# bottom frame for other widgets - which may use other layout manager
bottom = tk.Frame(root)
bottom.pack()
# create figure
fig = matplotlib.pyplot.Figure()
# create matplotlib canvas using `fig` and assign to widget `top`
canvas = FigureCanvasTkAgg(fig, top)
# get canvas as tkinter widget and put in widget `top`
canvas.get_tk_widget().pack()
canvas._tkcanvas.pack()
# --- plot ---
data = {"Week": ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
"App1" : [2.6,3.4,3.25,2.8,1.75,5,2],
"App2" : [2.5,2.9,3.0,3.3,3.4,5,3],
"App3" : [1.6,15,1.25,5.8,6.75,6,4]
}
new_df = pd.DataFrame(data)
ax = fig.add_subplot(111)
fig.suptitle('Graph Title', fontsize=12)
new_df.plot(x="Week", y=["App1", "App2", "App3"],ax=ax)
def on_closing():
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.lift()
root.attributes('-topmost',True)
root.mainloop()

Categories