If I pan the function in the following example, the axis position is moved in order to keep TEXT in the canvas. Is there a way to keep the axes and to treat TEXT just like the plotted line while keeping constrained_layout=true?
import tkinter as tk
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.backends.backend_tkagg as tkagg
class NewGUI():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('500x400+200+200')
self.plot_frame = tk.Frame()
self.plot_frame.place(x=10, y=10, relheight=0.7, relwidth=0.7, anchor='nw')
self.plot_window = Plotwindow(self, (18,12))
self.root.mainloop()
class Plotwindow():
def __init__(self, root, size):
fig = mpl.figure.Figure(size, constrained_layout=True)
ax = fig.add_subplot(111)
canvas = tkagg.FigureCanvasTkAgg(fig, master=root.plot_frame)
canvas.get_tk_widget().pack()
toolbar = tkagg.NavigationToolbar2Tk(canvas, root.root)
toolbar.update()
x = np.arange(0, 5, 0.1)
y = np.sin(x)
ax.plot(x, y)
ax.text(0, 0, 'TEXT')
if __name__ == '__main__':
new = NewGUI()
Related
I'm building a GUI using tkinter and matplotlib (and seaborn) to show a heatmap from a user chosen csv. I want the heatmap to update each time it's loaded, with the appropriate colorbar. I clear my axes each time I load new data in, but the colorbar never goes away, and the new heatmap squishes off to the side. I want the old colorbar to be cleared as well so the new heatmap can fill the space properly.
I made a MWE to show off my problem:
import numpy as np
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.state('zoomed')
self.winfo_toplevel().title('App')
frame = tk.Frame(self)
frame.pack()
button_reload = tk.Button(frame, text='Reload data', command=self.reload_data)
button_reload.pack()
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
self.fig.tight_layout() # Small margins
self.ax.axis('off') # Disable axis lines
self.canvas_heatmap = FigureCanvasTkAgg(self.fig, master=frame)
self.canvas_heatmap.get_tk_widget().pack(expand=True, fill='both')
def reload_data(self):
# dummy data for example
data = np.random.rand(3,3)
# Clear old heatmap from axes
self.ax.clear()
# Set up new heatmap
self.ax = sns.heatmap(data, ax=self.ax, linewidth=0.1)
self.canvas_heatmap.draw()
self.canvas_heatmap.get_tk_widget().pack(expand=True, fill='both') # necessary?
def quit_GUI():
root.quit()
root.destroy()
if __name__ == '__main__':
root = App()
root.protocol('WM_DELETE_WINDOW', quit_GUI) # Kill process on clicking 'X'
root.mainloop()
Here are some photos where you can see the colorbars sticking around when I don't want them to.
GOOD SO FAR:
BAD:
WORSE:
I could keep going like this until my heatmap is a sliver.
You need to clear the figure and remake the ax.
import numpy as np
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.state('zoomed')
self.winfo_toplevel().title('App')
frame = tk.Frame(self)
frame.pack()
button_reload = tk.Button(frame, text='Reload data', command=self.reload_data)
button_reload.pack()
self.fig = Figure()
self.canvas_heatmap = FigureCanvasTkAgg(self.fig, master=frame)
self.canvas_heatmap.get_tk_widget().pack(expand=True, fill='both')
def reload_data(self):
data = np.random.rand(3,3)
self.fig.clear()
ax = self.fig.add_subplot(111)
ax.axis('off') # Disable axis lines
line = sns.heatmap(data, ax=ax, linewidth=0.1)
self.fig.tight_layout() # Should go after the drawing
self.canvas_heatmap.draw()
# ~ self.canvas_heatmap.get_tk_widget().pack(expand=True, fill='both') # not necessary
if __name__ == '__main__':
root = App()
# ~ root.protocol('WM_DELETE_WINDOW', quit_GUI) # not needed
root.mainloop()
I'm trying to automatically update a chart in tkinter continuously using FigureCanvasTkAgg without the use of buttons.
Here is what I've coded so far
import random
import tkinter as tk
import seaborn as sb
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root = tk.Tk()
def cplot():
xCord = [random.randint(0,10) for i in range(5)]
yCord = [random.randint(0,10) for i in range(5)]
#defining heatmap dimensions
fig, ax = plt.subplots()
#ploting heat map with x and y coordinates
sb.kdeplot(xCord, yCord, shade = True, cmap = "Reds")
ax.invert_yaxis()
plt.axis("off")
plt.show()
root.after(1, cplot)
return fig
fig = cplot()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.after(1, cplot)
root.mainloop()
To have the plot image regenerate on a timer, recreate the canvas widget inside the function and recall the function.
Try this code:
import random
import tkinter as tk
import seaborn as sb
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root = tk.Tk()
canvas = None
def cplot():
global canvas
xCord = [random.randint(0,10) for i in range(5)]
yCord = [random.randint(0,10) for i in range(5)]
#defining heatmap dimensions
fig, ax = plt.subplots()
#ploting heat map with x and y coordinates
sb.kdeplot(xCord, yCord, shade = True, cmap = "Reds")
ax.invert_yaxis()
plt.axis("off")
if canvas: canvas.get_tk_widget().pack_forget() # remove previous image
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.after(100, cplot)
root.after(1, cplot)
root.mainloop()
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()
I'm working on curve fitting using the Radial Basis Neural Network. I have succeeded in embedding my plot to the tkinter canvas after following this guide.
My problem however is that when I run my code, the plot does not display in the canvas unless I either expand or contract the GUI window. I have searched for related problems here but I couldn't find one addressing specifically this issue. I am using python 3.4.2.
from tkinter import *
import math
import numpy as np
from numpy import *
import scipy
import scipy.linalg
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
class RadialBasisNetwork:
def __init__(self):
window = Tk()
window.title("RBF Curve Fitting")
self.f = Figure(figsize=(4,3), dpi=100)
self.canvas = FigureCanvasTkAgg(self.f, master=window)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)
self.canvas._tkcanvas.pack(side=LEFT, fill=BOTH, expand=1)
frame0 = Frame(window)
frame0.pack(fill=BOTH, expand=1)
title = Label(frame0, text = "RBF Network Controller", font = "Times 12 bold")
title.grid(row = 1, column = 1)
def Plot(self):
x = np.linspace(x_0, x_1, num = steps) # generate domain of x
plot_title = "model of " + model
a = self.f.add_subplot(111)
a.plot(x,ypred, 'r--') # plot x against predicted y
a.plot(x,y) # plot x against actual y (target)
a.legend(["Fit", "Target"], loc = "best", frameon = False, labelspacing = 0)
a.set_title(plot_title)
a.set_ylabel('Y axis')
a.set_xlabel('X axis')
RadialBasisNetwork()
For a project I am working on a simple harmonic motion simulator (How a mass oscillates over time). I have got the data produced correctly and already have a graph produced within a tkinter frame work. At the moment it only shows a static graph where my objective is to display the graph as an animation over time.
So for ease sake I have created a mock up of the programme using the following code:
#---------Imports
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as Tk
from tkinter import ttk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#---------End of imports
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01) # x-array
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), interval=25, blit=False)
#plt.show() #What I want the object in tkinter to appear as
root = Tk.Tk()
label = ttk.Label(root,text="SHM Simulation").grid(column=0, row=0)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().grid(column=0,row=1)
Tk.mainloop()
This code will display the animation that I want in the tkinter frame work when the plt.show() is uncommented. I would like to be able to place that animation within the framework of tkinter.
I have also been on the matplotlib website and viewed all of the animation examples and none of them have helped. I have also looked on Embedding an animated matplotlib in tk and that has placed the tkinter button within pyplot figure, whereas I would like to place the figure within a tkinter frame.
So just to clarify, I would like to be able to place the animation produced when plt.show() is uncommented in a tkinter frame, ie root = tk().
I modified your code:
#---------Imports
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as Tk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#---------End of imports
fig = plt.Figure()
x = np.arange(0, 2*np.pi, 0.01) # x-array
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
root = Tk.Tk()
label = Tk.Label(root,text="SHM Simulation").grid(column=0, row=0)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(column=0,row=1)
ax = fig.add_subplot(111)
line, = ax.plot(x, np.sin(x))
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), interval=25, blit=False)
Tk.mainloop()
Based on the answer of user151522 that didnt work for me at the first try, i made a few modifications to work in python 3.7:
#---------Imports
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#---------End of imports
from tkinter import Frame,Label,Entry,Button
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def Clear(self):
print("clear")
self.textAmplitude.insert(0, "1.0")
self.textSpeed.insert(0, "1.0")
def Plot(self):
self.v = float(self.textSpeed.get())
self.A = float(self.textAmplitude.get())
def animate(self,i):
self.line.set_ydata(self.A*np.sin(self.x+self.v*i)) # update the data
return self.line,
def init_window(self):
self.master.title("Use Of FuncAnimation in tkinter based GUI")
self.pack(fill='both', expand=1)
#Create the controls, note use of grid
self.labelSpeed = Label(self,text="Speed (km/Hr)",width=12)
self.labelSpeed.grid(row=0,column=1)
self.labelAmplitude = Label(self,text="Amplitude",width=12)
self.labelAmplitude.grid(row=0,column=2)
self.textSpeed = Entry(self,width=12)
self.textSpeed.grid(row=1,column=1)
self.textAmplitude = Entry(self,width=12)
self.textAmplitude.grid(row=1,column=2)
self.textAmplitude.insert(0, "1.0")
self.textSpeed.insert(0, "1.0")
self.v = 1.0
self.A = 1.0
self.buttonPlot = Button(self,text="Plot",command=self.Plot,width=12)
self.buttonPlot.grid(row=2,column=1)
self.buttonClear = Button(self,text="Clear",command=self.Clear,width=12)
self.buttonClear.grid(row=2,column=2)
self.buttonClear.bind(lambda e:self.Clear)
tk.Label(self,text="SHM Simulation").grid(column=0, row=3)
self.fig = plt.Figure()
self.x = 20*np.arange(0, 2*np.pi, 0.01) # x-array
self.ax = self.fig.add_subplot(111)
self.line, = self.ax.plot(self.x, np.sin(self.x))
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.get_tk_widget().grid(column=0,row=4)
self.ani = animation.FuncAnimation(self.fig, self.animate, np.arange(1, 200), interval=25, blit=False)
root = tk.Tk()
root.geometry("700x400")
app = Window(root)
tk.mainloop()
This answer will hopefully be allowed. It is an answer to what I was actually interested in, when I initially found this question, that is, 'Embedding a Matplotlib animation into a tkinter based GUI'.
The code that gave the previous screenshot has been extended, in this code the canvas has been placed inside a class definition, together with some code for two command buttons, these buttons don't actually do "anything" but the structure is there for possible further development.
The following screenshot was produced with the aid of the extended code
A screenshot of the SHM animation running from within a tkinter based GUI
The extended code used for the above screenshot is given below.
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
from tkinter import Frame,Label,Entry,Button
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def Clear(self):
x=0
# def Plot(self):
# x=0
def init_window(self):
def animate(i):
self.line.set_ydata(np.sin(self.x+i/10.0)) # update the data
return self.line,
self.master.title("Use Of FuncAnimation in tkinter based GUI")
self.pack(fill='both', expand=1)
#Create the controls, note use of grid
self.labelSpeed = Label(self,text="Speed (km/Hr)",width=12)
self.labelSpeed.grid(row=0,column=1)
self.labelAmplitude = Label(self,text="Amplitude",width=12)
self.labelAmplitude.grid(row=0,column=2)
self.textSpeed = Entry(self,width=12)
self.textSpeed.grid(row=1,column=1)
self.textAmplitude = Entry(self,width=12)
self.textAmplitude.grid(row=1,column=2)
# self.buttonPlot = Button(self,text="Plot",command=self.Plot,width=12)
self.buttonPlot = Button(self,text="Plot",width=12)
self.buttonPlot.grid(row=2,column=1)
self.buttonClear = Button(self,text="Clear",command=self.Clear,width=12)
self.buttonClear.grid(row=2,column=2)
# self.buttonClear.bind(lambda e:self.Plot)
self.buttonClear.bind(lambda e:self.Clear)
tk.Label(self,text="SHM Simulation").grid(column=0, row=3)
self.fig = plt.Figure()
self.x = np.arange(0, 2*np.pi, 0.01) # x-array
self.ax = self.fig.add_subplot(111)
self.line, = self.ax.plot(self.x, np.sin(self.x))
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.get_tk_widget().grid(column=0,row=4)
self.ani = animation.FuncAnimation(self.fig, animate, np.arange(1, 200), interval=25, blit=False)
root = tk.Tk()
root.geometry("700x400")
app = Window(root)
tk.mainloop()