The following codes is to plot contours from five (slider: 0 ~ 4) .xlsx files on tkinter
. Each file just contains numerical data in the matrix 12X6 such as
JavaScript
x
70
70
1
from tkinter import *
2
import tkinter.ttk as ttk
3
import matplotlib
4
import matplotlib.pyplot as plt
5
from matplotlib import cm
6
import numpy as np
7
import ipywidgets as wg
8
import os
9
import pandas as pd
10
from matplotlib.ticker import MaxNLocator
11
from matplotlib.colors import BoundaryNorm
12
import math
13
from matplotlib.ticker import LinearLocator
14
%matplotlib widget
15
from matplotlib.widgets import Slider
16
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
17
matplotlib.use('TkAgg')
18
19
root = Tk()
20
root.title('TEST')
21
root.geometry("800x800")
22
23
def plot_noise():
24
rec = np.shape(dfs[0])
25
rmm = np.concatenate([dfs[0], dfs[1]])
26
for jj in range(2,num):
27
rmm = np.concatenate([rmm, dfs[jj]])
28
# =================================================PLOT===========================================
29
fig = plt.Figure()
30
canvas = FigureCanvasTkAgg(fig, root)
31
canvas.get_tk_widget().grid(row=3, column=0, columnspan=3, rowspan=3, sticky=W+E+N+S, padx=0, pady=0)
32
33
# ===============================================contourf=========================================
34
ax = fig.add_subplot(111)
35
fig.subplots_adjust(bottom=0.25)
36
X = np.arange(1,rec[1]+1,1)
37
Y = np.arange(1,rec[0]+1,1)
38
x , y = np.meshgrid(X,Y)
39
# ==============================================color bar=========================================
40
cbar_max = math.floor(np.min(rmm))
41
cbar_min = math.ceil(np.max(rmm))
42
cbar_num_colors = 200
43
cbar_num_format = "%d"
44
levels = MaxNLocator(nbins=cbar_num_colors).tick_values(cbar_min, cbar_max)
45
# ============================================Initial plot========================================
46
con = ax.contourf(x,y,dfs[1], levels = levels, cmap=cm.jet, alpha = 0.5, antialiased = True)
47
cbar = fig.colorbar(con,ax = ax)
48
ax.axis([1, 12, 1, 6])
49
# ================================================Slider==========================================
50
global slider_de
51
slider_bar = fig.add_axes([0.12, 0.1, 0.78, 0.03])
52
slider_de = Slider(slider_bar, 's_bar', 0, num-1, valinit=1,valfmt='%0.0f', valstep=1)
53
num_on_slider = []
54
def update(val):
55
num_on_slider.append(slider_de.val)
56
for ii in range(0,num):
57
if num_on_slider[-1] == ii:
58
con = ax.contourf(x,y,dfs[ii], levels = levels, cmap=cm.jet, alpha = 0.5, antialiased = True)
59
cbar = fig.colorbar(con,ax = ax)
60
ax.axis([1, 12, 1, 6])
61
62
slider_de.on_changed(update)
63
64
65
# =================================================GUI - Tkinter=======================================
66
resultButton = ttk.Button(root, text = 'show', command = plot_noise)
67
resultButton.grid(column=0, row=1, pady=15, sticky=W)
68
69
root.mainloop()
70
When running it, I got
Now, if I use fig.clf
, for example
JavaScript
1
4
1
fig.clf()
2
con = ax.contourf(x,y,dfs[ii], levels = levels, cmap=cm.jet, alpha = 0.5, antialiased = True)
3
cbar = fig.colorbar(con,ax = ax)
4
I got
The contour disappeared. I also tried from matplotlib.figure import Figure
instead of pyplot; however, it does not work.
How to fix this odd problem?
Any advices please, thanks!
Advertisement
Answer
Refactored code into a class and added feature to select folder. Other ideas are in the comments.
JavaScript
1
100
100
1
#Do not use wild imports
2
import tkinter as tk
3
import tkinter.ttk as ttk
4
import matplotlib
5
import matplotlib.pyplot as plt
6
from matplotlib import cm
7
import numpy as np
8
import ipywidgets as wg
9
import os
10
import pandas as pd
11
from matplotlib.ticker import MaxNLocator
12
from matplotlib.colors import BoundaryNorm
13
import math
14
from matplotlib.ticker import LinearLocator
15
from matplotlib.widgets import Slider
16
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
17
matplotlib.use('TkAgg')
18
19
20
class MyPlot(ttk.Frame):
21
def __init__(self, parent):
22
super().__init__()
23
24
#put widgets in frame(self)
25
resultButton = ttk.Button(self, text = 'Select Folder', command = self.select_dir)
26
resultButton.grid(column=0, row=1, pady=15, sticky=tk.W)
27
28
# show frame in root
29
self.grid(column=0, row=0)
30
31
def select_dir(self):
32
selected_dir = tk.filedialog.askdirectory(parent=self, title='Select a directory')
33
# print(selected_dir)
34
if selected_dir:
35
self.plot_noise(selected_dir)
36
else:
37
tk.messagebox.showerror('Select', 'Select a directory', parent=self)
38
39
def plot_noise(self, folder):
40
# ============================================Read .xlsx file=====================================
41
files = os.listdir(folder)
42
dfs = {}
43
# Prepare for scenarios where files(other than the expected .xlsx) are in the folder passed
44
# when that is the case the enumerated i previously being used to create dict keys will get all messed up
45
index = 0
46
for file in files:
47
if file.endswith('.xlsx'):
48
dfs[index] = pd.read_excel(os.path.join(folder,file), sheet_name='Z=143', header = None, skiprows=[0], usecols = "B:M")
49
index += 1
50
51
if dfs:
52
num = len(dfs)
53
rec = np.shape(dfs[0])
54
rmm = np.concatenate([dfs[0], dfs[1]])
55
for jj in range(2,num):
56
rmm = np.concatenate([rmm, dfs[jj]])
57
# =================================================PLOT===========================================
58
fig, ax = plt.subplots()
59
canvas = FigureCanvasTkAgg(fig, self)
60
canvas.get_tk_widget().grid(row=3, column=0, columnspan=3, rowspan=3, sticky=tk.W+tk.E+tk.N+tk.S, padx=0, pady=0)
61
# ===============================================contourf=========================================
62
fig.subplots_adjust(bottom=0.25)
63
X = np.arange(1,rec[1]+1,1)
64
Y = np.arange(1,rec[0]+1,1)
65
x , y = np.meshgrid(X,Y)
66
# ==============================================color bar=========================================
67
cbar_max = math.floor(np.min(rmm))
68
cbar_min = math.ceil(np.max(rmm))
69
cbar_num_colors = 200
70
cbar_num_format = "%d"
71
levels = MaxNLocator(nbins=cbar_num_colors).tick_values(cbar_min, cbar_max)
72
# ============================================Initial plot========================================
73
con = ax.contourf(x,y,dfs[1], levels = levels, cmap=cm.jet, alpha = 0.5, antialiased = True)
74
cbar = fig.colorbar(con,ax = ax)
75
ax.axis([1, 12, 1, 6])
76
# ================================================Slider==========================================
77
slider_bar = fig.add_axes([0.12, 0.1, 0.78, 0.03])
78
slider_de = Slider(slider_bar, 's_bar', 0, num-1, valinit=1,valfmt='%0.0f', valstep=1)
79
num_on_slider = []
80
81
def update(val):
82
num_on_slider.append(slider_de.val)
83
for ii in range(0,num):
84
if num_on_slider[-1] == ii:
85
con = ax.contourf(x,y,dfs[ii], levels = levels, cmap=cm.jet, alpha = 0.5, antialiased = True)
86
ax.axis([1, 12, 1, 6])
87
88
slider_de.on_changed(update)
89
90
else:
91
tk.messagebox.showerror('No File', 'No .xlsx file found')
92
93
94
# =================================================GUI - Tkinter=======================================
95
root = tk.Tk()
96
root.title('TEST')
97
root.geometry("800x800")
98
MyPlot(root)
99
root.mainloop()
100