How to overlay multiple plots on the same chart tkinter - python

I am new to tkinter and python and trying to write a simple program that lets me overlay line charts on the same plot. The code I have written (some taken from the 'matplotlib' site) keeps placing all the charts underneath each other. Is there a simpler way to do this. I cant seem to take the canvas or widgets outside the 'for' loop without it messing something up,my code and test 'csv' files are below.Any help or guidance please as to what I need to change?
from tkinter import ttk
import tkinter
from tkinter import *
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
current_list = ['Blue', 'Green', 'Yellow']
for item in current_list:
x, y = np.loadtxt(item + '_' + 'Test.csv', skiprows=1, usecols=[2, 3],
unpack=True, delimiter=',')
fig = Figure(figsize=(2, 3), dpi=100)
fig.add_subplot(111).plot(x, y)
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
# closed with the window manager.
csv test files - Blue_Test.csv
Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8
1,100,19,100,Blue,2000,1.00E-19,1.00E-09
2,110,20,101,Blue,3000,5.00E-19,1.00E+00
3,120,21,102,Blue,4000,9.00E-19,2.00E+00
4,150,24,105,Blue,7000,2.10E-18,5.00E+00
5,160,25,106,Blue,8000,2.50E-18,6.00E+00
## csv test files - Green_Test.csv
Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8
1,100,19,2000,Green,2000,1.00E-19,1.00E-09
2,110,20,3001,Green,3000,5.00E-19,1.00E+00
3,120,21,4002,Green,4000,9.00E-19,2.00E+00
4,150,24,5005,Green,7000,2.10E-18,5.00E+00
5,160,25,6006,Green,8000,2.50E-18,6.00E+00
## csv test files - Yellow_Test.csv
Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8
1,100,19,11000,Yellow,2000,1.00E-19,1.00E-09
2,110,20,12001,Yellow,3000,5.00E-19,1.00E+00
3,120,21,13002,Yellow,4000,9.00E-19,2.00E+00
4,150,24,14005,Yellow,7000,2.10E-18,5.00E+00
5,160,25,15006,Yellow,8000,2.50000,5.000000

The problem lies in the for item in current_list: loop, in each iteration of the loop the code creates a new subplot and draws it on the canvas. Instead, you should create one subplot and plot each dataset on it. Then once the loop has completed, draw the populated subplot on the canvas. https://pydatascience.org/2017/11/24/plot-multiple-lines-in-one-chart-with-different-style-python-matplotlib/
import tkinter
import numpy as np
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
current_list = ['Blue', 'Green', 'Yellow']
fig = Figure(figsize=(2, 3), dpi=100)
ax = fig.add_subplot(111)
for item in current_list:
x, y = np.loadtxt(item + '_' + 'Test.csv', skiprows=1, usecols=[2, 3],
unpack=True, delimiter=',')
ax.plot(x, y, label=item)
fig.legend()
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
# closed with the window manager.

Related

Unable to embed networkx graph using matplotlib in customtk

I'm trying to embed a networkx graph in CustomTk, but the graph doesn't appear. When I use plt.show() I can see the graph in matplotlib pop-up menu, but not in GUI.
import tkinter
import customtkinter
import networkx as nx
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
root = customtkinter.CTk()
root.title("Embedding in Tk")
fig = Figure(figsize=(5, 4), dpi=100)
G = nx.random_geometric_graph(20, 0.125, seed=896803)
nx.draw_networkx(G, pos=nx.circular_layout(G), node_size=4000, with_labels=True, font_size=20)
plt.style.use('ggplot')
fig = Figure(figsize=(10, 10), dpi=100)
ax = fig.add_subplot(111)
ax = plt.gca()
ax.margins(0.11)
plt.tight_layout()
plt.axis("off")
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
plt.show()
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = customtkinter.CTkButton(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
root.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
# closed with the window manager.
plt.show() image:
figure on canvas:
I'm not sure what's the issue when drawing on the canvas.
Thanks in advance
Solution: https://github.com/TomSchimansky/CustomTkinter/issues/971#issuecomment-1371489896
import tkinter
import customtkinter
import networkx as nx
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
root = customtkinter.CTk()
root.title("Embedding in Tk")
#call fig ax exactly once
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
ax.margins(0.11)
#call the graphing module
G = nx.random_geometric_graph(20, 0.125, seed=896803)
#draw the graph, note the ax=ax at the end, this is the critical part, matplotlib needs to know onto which axis the graph is drawn
#otherwise it will just draw it in the spyder backend, without a care for your other elements
nx.draw(G, pos=nx.circular_layout(G), node_size=4000, with_labels=True, font_size=20,ax=ax)
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = customtkinter.CTkButton(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
root.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
# closed with the window manager.

How to change color of matplotlib toolbar in tkinter?

I would like to change the color of the toolbar when making a matplotlib figure in tkinter. I have managed to find and change the color of two parts. There is one remaining.
My code comes directly from https://matplotlib.org/stable/gallery/user_interfaces/embedding_in_tk_sgskip.html?highlight=embedding%20tk with three additional lines to change colors.
import tkinter
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import numpy as np
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot().plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
color = "#d469a3"
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.config(background=color)
toolbar._message_label.config(background=color)
toolbar.update()
button = tkinter.Button(master=root, text="Quit", command=root.quit)
button.pack(side=tkinter.BOTTOM)
toolbar.pack(side=tkinter.BOTTOM)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
tkinter.mainloop()
This gives me the window:
What is the small, grey rectangle I have pointed out? How do I change its color?
It is an empty label. You can get a reference to it via winfo_children:
print (toolbar.winfo_children()[-2])
# .!navigationtoolbar2tk.!label
And to change its color:
toolbar.winfo_children()[-2].config(background=color)

matplotlib add to panedwindow in tkinter

I do not understand how correctly add matplotlib into panedwindow of tkinter.
I want to have on one side list box and matplotlib interactive plot, on the other side
I need to resize listbox and plot by dragging boundary between them
this is what is desirable
I tried this but I cannot add correctly matplot lib to paned window
from tkinter import *
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
root = Tk()
m = PanedWindow(root)
m.pack(fill=BOTH, expand=1)
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTkAgg(fig, master = root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=RIGHT, fill=BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=RIGHT, fill=BOTH, expand=1)
m.add(toolbar)
m.add(canvas)
lstbox2 = Listbox(selectmode=MULTIPLE, width=20, height=10)
m.add(lstbox2)
root.mainloop()
Put your canvas and toolbar in a Frame instead, and add that Frame to your paned window:
root = Tk()
...
canvas_frame = Frame(root)
canvas = FigureCanvasTkAgg(fig, master = canvas_frame)
canvas.draw()
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2Tk(canvas, canvas_frame)
toolbar.update()
toolbar.pack_configure(expand=True)
m.add(canvas_frame)
lstbox2 = Listbox(selectmode=MULTIPLE, width=20, height=10)
m.add(lstbox2)
root.mainloop()

How to use same NavigationToolbar2Tk for multiple matplotlib plots

I've got multiple pages in a notebook and have multiple graphs on each.
Is there a way to use one navigation toolbar for all graphs on a notebook page? Or how can I put each navigation toolbar directly underneath the graph it controls?
I've tried adding padx and pady which I thought would force it under the graph, but it keeps putting both toolbars underneath the Quit button.
I'm pretty new to Python and am really struggling to find an answer to this question!
import numpy as np
import matplotlib.pyplot as plt
import tkinter as app
from tkinter import ttk
from matplotlib.collections import LineCollection
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
x = np.linspace(1, 10, 10)
y = np.square(x)
z = x
#Make the root widget
root = app.Tk()
#Make the notebook
nb = ttk.Notebook(root)
nb.pack()
root.title("Test")
#plot first graph
f1 = app.Frame(nb)
nb.add(f1, text="Test")
app.Label(f1, text="Test window 1").pack(padx=5, pady=5)
fig1 = Figure(figsize=(5, 4), dpi=100)
fig1.add_subplot(111).plot(x, y)
canvas1 = FigureCanvasTkAgg(fig1, master=f1)
canvas1.draw()
canvas1.get_tk_widget().pack(side=app.TOP, fill=app.BOTH, expand=1)
#add toolbar
toolbar1 = NavigationToolbar2Tk(canvas1, f1)
toolbar1.update()
canvas1.get_tk_widget().pack(side=app.TOP, fill=app.BOTH, expand=1)
#plot second graph
fig2 = Figure(figsize=(5, 4), dpi=100)
fig2.add_subplot(111).plot(x, z)
canvas2 = FigureCanvasTkAgg(fig2, master=f1)
canvas2.draw()
canvas2.get_tk_widget().pack(side=app.TOP, fill=app.BOTH, expand=1, padx=5, pady=5)
#add toolbar
toolbar2 = NavigationToolbar2Tk(canvas2, f1)
toolbar2.update()
canvas2.get_tk_widget().pack(side=app.TOP, fill=app.BOTH, expand=1)
app.Button(f1, text='Exit', command=root.destroy).pack(padx=50, pady=50)
nb.select(f1)
nb.enable_traversal()
#Enter the mainloop
root.mainloop()

How do you change the plot background color in a tkinter application?

I have a plot in a tkinter application and I am trying to change the background color of the plot using tkinter colors. I have found How to change plot background color? however, I got this error:
ValueError: Invalid RGBA argument: 'AntiqueWhite2'
...indicating I may only be able to use their subset of colors? Does anyone know how to use the tkinter colors here?
Here is what I am currently using (without color change):
self.fig = Figure(figsize=(5, 4), dpi=100)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.master) # A tk.DrawingArea
self.canvas.draw()
self.ax = self.fig.add_subplot(111)
import tkinter
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np
root = tkinter.Tk()
root.geometry("770x633+745+171")
Frame1 = tkinter.Frame(root)
Frame1.place(relx=0.1, rely=0.1, relheight=0.3, relwidth=0.5)
root.wm_title("Embedding in Tk")
t = np.arange(0, 3, .01)
fig = Figure(figsize=(5, 3), dpi=80,facecolor = 'k')
axes1 =fig.add_subplot(111)
# axes1.axis('tight')
axes1.autoscale(enable=True, axis='y', tight=True)
axes1.plot(t, 2 * np.sin(2 * np.pi * t))
# axes1.set_axis_bgcolor('k')
axes1.set_facecolor('k')
axes1.grid(color = 'w')
for label in axes1.xaxis.get_ticklabels():
# label is a Text instance
label.set_color('w')
for label in axes1.yaxis.get_ticklabels():
# label is a Text instance
label.set_color('w')
# label.set_rotation(45)
# label.set_fontsize(1)
for line in axes1.yaxis.get_ticklines():
# line is a Line2D instance
line.set_color('w')
for line in axes1.xaxis.get_ticklines():
# line is a Line2D instance
line.set_color('w')
# line.set_markersize(25)
# line.set_markeredgewidth(3)
for line in axes1.xaxis.get_gridlines():
line.set_color('w')
for line in axes1.yaxis.get_gridlines():
line.set_color('w')
line.set_markeredgewidth(8)
axes1.yaxis.grid(color='w',linewidth=1)
# axes1.set_xmargin(0.9)
axes1.set_xlabel("Time(ns)")
axes1.xaxis.label.set_color('w')
axes1.set_ylabel("Amplitude(mV)")
axes1.yaxis.label.set_color('w')
axes1.xaxis.grid(color='w',linewidth=1)
axes1.spines['bottom'].set_color('white')
axes1.spines['top'].set_color('white')
axes1.spines['left'].set_color('white')
axes1.spines['right'].set_color('white')
canvas = FigureCanvasTkAgg(fig, master=Frame1) # A tk.DrawingArea.
canvas.get_tk_widget().configure(bg='black')
canvas.get_tk_widget().grid(row=1,column=0)
canvas.get_tk_widget().grid(row=1,column=0)
# canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
fig.tight_layout()
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
# plt.tight_layout()
This is an example for change the background as black and change the label, grid, tick labels, ... color.

Categories