def show_histogram(self):
"""Generate histogram
event - STRING - sent by self.x_column_selector when a column is selected"""
column_name = self.x_column_selected.get()
# histogram generated here - reference the canvas() method for the variable names to generate the plot
print("Histogram with " + column_name + " x column to be generated")
self.f = Figure(figsize = (6,4), dpi = 100)
self.a = self.f.add_subplot(111)
self.a = self.histogram_object.generate(column_name, self.a, color = self.plot_color)
self.canvas = FigureCanvasTkAgg(self.f, master=self)
self.canvas.get_tk_widget().grid(column=3, row=1, rowspan=5, sticky="nesw")
python类FigureCanvasTkAgg()的实例源码
def show_scatter_plot(self):
"""Generate scatter plot
event - STRING - sent by self.x_column_selector or self.y_column_selector when a column is selected"""
x_column_name = self.x_column_selected.get()
y_column_name = self.y_column_selected.get()
# scatter plot generated here - reference the canvas() method for the variable names to generate the plot
if x_column_name == "" or y_column_name == "":
print("Both columns are not filled wont generate scatter plot")
elif x_column_name == y_column_name:
# print("Both columns are the same cannot plot")
self.same_columns_warning_label.grid()
self.same_columns_warning_label_isVisible = True
else:
# make sure warning label isnt there
if self.same_columns_warning_label_isVisible == True:
self.same_columns_warning_label.grid_remove()
self.same_columns_warning_label_isVisible = False
self.f = Figure(figsize = (6,4), dpi = 100)
self.a = self.f.add_subplot(111)
self.a = self.scatter_object.generate(x_column_name, y_column_name, self.a, color = self.plot_color)
self.canvas = FigureCanvasTkAgg(self.f, master=self)
self.canvas.get_tk_widget().grid(column=3, row=1, rowspan=5, sticky="nesw")
def show_regression_scatter_plot(self):
"""Generate scatter plot with a regression line
event - STRING - sent by self.x_column_selector or self.y_column_selector when a column is selected"""
x_column_name = self.x_column_selected.get()
y_column_name = self.y_column_selected.get()
# scatter plot generated here - reference the canvas() method for the variable names to generate the plot
if x_column_name == "" or y_column_name == "":
print("Both columns are not filled wont generate scatter plot")
elif x_column_name == y_column_name:
# print("Both columns are the same cannot plot")
self.same_columns_warning_label.grid()
self.same_columns_warning_label_isVisible = True
else:
# make sure warning label isnt there
if self.same_columns_warning_label_isVisible == True:
self.same_columns_warning_label.grid_remove()
self.same_columns_warning_label_isVisible = False
self.f = Figure(figsize = (6,4), dpi = 100)
self.a = self.f.add_subplot(111)
self.a = self.scatter_object.lin_generate(x_column_name, y_column_name, self.a, color = self.plot_color)
self.canvas = FigureCanvasTkAgg(self.f, master=self)
self.canvas.get_tk_widget().grid(column=3, row=1, rowspan=5, sticky="nesw")
def create_canvas(self):
"""Creates a canvas object to draw matplotlib visualizations on
self.f - Figure - contains the figure object for all of the subplots
self.a - Plot - the plot in question.
self.canvas - FigureCanvasTkAgg - tkinter widget that holds figure"""
self.f = Figure(figsize = (6,4), dpi = 100)
self.a = self.f.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.f, master=self)
self.canvas.get_tk_widget().grid(column=3, row=1, rowspan=5, columnspan = 6, sticky="nesw")
self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.master) #do we want to keep this? it allows the user to save the plot so probs useful
def show_scatter_plot(self):
"""Generate scatter plot
event - STRING - sent by self.x_column_selector or self.y_column_selector when a column is selected"""
x_column_name = self.x_column_selected.get()
y_column_name = self.y_column_selected.get()
# scatter plot generated here - reference the canvas() method for the variable names to generate the plot
if x_column_name == "" or y_column_name == "":
print("Both columns are not filled wont generate scatter plot")
elif x_column_name == y_column_name:
# print("Both columns are the same cannot plot")
self.same_columns_warning_label.grid()
self.same_columns_warning_label_isVisible = True
else:
# make sure warning label isnt there
if self.same_columns_warning_label_isVisible == True:
self.same_columns_warning_label.grid_remove()
self.same_columns_warning_label_isVisible = False
self.f = Figure(figsize = (6,4), dpi = 100)
self.a = self.f.add_subplot(111)
self.a = self.scatter_object.generate(x_column_name, y_column_name, self.a, color = self.plot_color)
self.canvas = FigureCanvasTkAgg(self.f, master=self)
self.canvas.get_tk_widget().grid(column=3, row=1, rowspan=5, sticky="nesw")
def show_regression_scatter_plot(self):
"""Generate scatter plot with a regression line
event - STRING - sent by self.x_column_selector or self.y_column_selector when a column is selected"""
x_column_name = self.x_column_selected.get()
y_column_name = self.y_column_selected.get()
# scatter plot generated here - reference the canvas() method for the variable names to generate the plot
if x_column_name == "" or y_column_name == "":
print("Both columns are not filled wont generate scatter plot")
elif x_column_name == y_column_name:
# print("Both columns are the same cannot plot")
self.same_columns_warning_label.grid()
self.same_columns_warning_label_isVisible = True
else:
# make sure warning label isnt there
if self.same_columns_warning_label_isVisible == True:
self.same_columns_warning_label.grid_remove()
self.same_columns_warning_label_isVisible = False
self.f = Figure(figsize = (6,4), dpi = 100)
self.a = self.f.add_subplot(111)
self.a = self.scatter_object.lin_generate(x_column_name, y_column_name, self.a, color = self.plot_color)
self.canvas = FigureCanvasTkAgg(self.f, master=self)
self.canvas.get_tk_widget().grid(column=3, row=1, rowspan=5, sticky="nesw")
def create_canvas(self):
"""Creates a canvas object to draw matplotlib visualizations on
self.f - Figure - contains the figure object for all of the subplots
self.a - Plot - the plot in question.
self.canvas - FigureCanvasTkAgg - tkinter widget that holds figure"""
self.f = Figure(figsize = (6,4), dpi = 100)
self.a = self.f.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.f, master=self)
self.canvas.get_tk_widget().grid(column=3, row=1, rowspan=5, columnspan = 6, sticky="nesw")
self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.master) #do we want to keep this? it allows the user to save the plot so probs useful
def __init__(self, a1, a2, size):
self.a1 = a1;
self.a2 = a2;
self.size = size;
self.x = np.arange(-1 * self.size, self.size, 0.01);
self.y = np.arange(-1 * self.size, self.size, 0.01);
self.pointsX = [];
self.pointsY = [];
self.non = 0;
self.distances = [];
root = Tk.Tk()
root.wm_title("Embedding in TK")
self.f = Figure()
self.plt = self.f.add_subplot(1, 1, 1)
self.main();
self.update();
# a tk.DrawingArea
self.canvas = FigureCanvasTkAgg(self.f, master=root)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
nextBtn = Tk.Button(master=root, text='Next', command=self.next)
backBtn = Tk.Button(master=root, text='Back', command=self.back)
quitBtn = Tk.Button(master=root, text='Quit', command=sys.exit)
nextBtn.pack(side=Tk.RIGHT)
backBtn.pack(side=Tk.RIGHT)
quitBtn.pack(side=Tk.LEFT)
Tk.mainloop()
def __create_gui(self):
# Add subplots
self.figure = Mat_figure(figsize=(5, 3), dpi=100)
self.subplotTop = self.figure.add_subplot(211)
self.subplotBottom = self.figure.add_subplot(212)
# Add labels
self.subplotTop.set_xlabel('Frames')
self.subplotBottom.set_xlabel('Hz')
# Change font size
matplotlib.rcParams.update({'font.size': 10})
# Create canvas
self.canvas = FigureCanvasTkAgg(self.figure, master=self.root)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
# We store the data that is interchanged from GuiSignalProcessor to GuiSignalPlotter in a queue
self.dataQueue = LifoQueue()
# Create thread that displays signal
self.signalPlotThread = GuiSignalPlotter(self.root, self.cameraInstance, self.figure, self.canvas,
self.subplotTop, self.subplotBottom, self.statusbar,
self.video_display, self.dataQueue)
# Create thread that processes signal
self.signalProcessorThread = GuiSignalProcessor(self.root, self.cameraInstance, self.figure, self.canvas,
self.subplotTop, self.subplotBottom, self.statusbar,
self.video_display, self.dataQueue)
# Start both threads
self.signalPlotThread.start()
self.signalProcessorThread.start()
def setup_GUI(fig):
# working with GUI --------------------------------------------
print '\ninitializing...'
# print 'SHELL, "echo ' + '"Start Time:' + ' >> voxBuildTiming.log"'
# print 'SHELL, "echo %date% %time% >> voxBuildTiming.log"' # windows shell
# print 'SHELL, "date >> voxBuildTiming.log"' # linux shell
GUI = tk.Tk()
GUI.title('CSL - Autovox')
GUI.minsize(150,150)
GUI.geometry('1280x400+0+0')
f0 = tk.Frame(GUI) # defining frame
f0.pack(fill='both',expand=True)
f0_area = tk.Canvas(f0, width=10,height=10) # defining canvas area within frame
f0_area.pack(side=tk.TOP)
graph = FigureCanvasTkAgg(fig)
graph.show()
graph.pack()
# but1 = tk.Button(f0, text='Show Voxel Build', height=1, width=15, command= lambda: show_vox_build())
# but1.pack(side=tk.RIGHT)
# f0_area.create_window(10,10, window=but1)
GUI.mainloop()
# -------------------------------------------------------------
def create_app_graph(self):
""" Create app graph
"""
self.graph_figure = Figure(figsize=(4.4, 2.8), dpi=100)
self.graph = FigureCanvasTkAgg(self.graph_figure, master=self.frame_top)
self.graph.get_tk_widget().pack(side=LEFT, expand=NO, anchor=NW)
# EMBED GRAPH TOOLBAR
self.graph_toolbar = NavigationToolbar2TkAgg(self.graph, self.frame_bottom).pack(side=LEFT)
# PLOT STARTING PLOT
self.subplot = self.graph_figure.add_subplot(111)
self.lines = self.subplot.plot([1, 2, 3], [1, 2, 3])
self.change_xy_label('t(s)', 'magnitude')
def __loadMatplotlib(self):
global FigureCanvasTkAgg, Figure
if FigureCanvasTkAgg is None:
try:
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
except:
FigureCanvasTkAgg = Figure = False
def addPlot(
self,
title,
t, s,
row=None,
column=0,
colspan=0,
rowspan=0):
self.__verifyItem(self.n_plots, title, True)
self.__loadMatplotlib()
if FigureCanvasTkAgg is False:
raise Exception("Unable to load MatPlotLib - plots not available")
else:
fig = Figure()
axes = fig.add_subplot(111)
axes.plot(t,s)
canvas = FigureCanvasTkAgg(fig, self.__getContainer())
canvas.fig = fig
canvas.axes = axes
canvas.show()
# canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
self.__positionWidget(canvas.get_tk_widget(), row, column, colspan, rowspan)
self.n_plots[title] = canvas
return axes
def drawgraph(markethistory):
global graphdrawn
# Set up a graph and data sets
timeplots = []
priceplots = []
# Set up the graph
figgraph = Figure(figsize=(10, 10), dpi=60)
# 2D Graph : 1 column, 1 Row, 1 Plot
axes = figgraph.add_subplot(111)
for key in markethistory:
figgraph.suptitle(markethistory[key].Label)
price = markethistory[key].Price
timestamp = markethistory[key].Timestamp
dtplot = datetime.datetime.fromtimestamp(timestamp)
timeplots.insert(len(timeplots), dtplot)
priceplots.insert(len(priceplots), price)
# Enforce 8 decimal places
axes.yaxis.set_major_formatter(FormatStrFormatter('%.8f'))
# Plot the graph
axes.plot(timeplots, priceplots)
# Canvas placed in main frame, controlled by figgraph
window.canvas = FigureCanvasTkAgg(figgraph, master=window.mainframe)
window.canvas.get_tk_widget().place(relx=0.26, rely=0.01, relheight=0.46, relwidth=0.74)
window.canvas.draw()
graphdrawn = True
# Sell order list select event.
def plotarGraficos(self):
print "Gerando gráficos..."
fig = plt.figure(1) # cria um vetor de figuras para serem exibidos os gráficos
self.mainContainerPressao = Frame(self.frame_aba1, relief=RAISED, borderwidth=1)
self.mainContainerPressao.pack(expand="true", fill="both", side="top")
self.mainContainerCondutancia = Frame(self.frame_aba3, relief=RAISED, borderwidth=1)
self.mainContainerCondutancia.pack(expand="true", fill="both", side="top")
for i in range(1, 7):
for j in range(i+1, 7):
aux = pearson_def(self.valor[i], self.valor[j])
if aux < 97:
self.msgAlerta.config(text="Anomalia na coorelação entre " + str(self.descricao[i]) + " e " + str(self.descricao[j]) + "\n")
self.msgAlerta.pack()
for i in range(1, 7): # adiciona os gráficos no vetor
plot = plt.subplot(230+i)
plt.title(str(self.descricao[i]), fontsize=11)
plot.tick_params(axis='both', which='major', labelsize=6)
plot.tick_params(axis='both', which='minor', labelsize=7)
tempLim = savgol_filter(self.valor[i], 27, 2) # aplica o filtro de Savitzky-Golay
# A linha abaico comentada apresenta junto com a linha de dados do gráfico, os limiares superiores e inferiores aceitaveis calculados pelo filtro de Savitzky-Golay, esta função se encontra em testes
#plt.plot(self.data_mensagem[i], self.valor[i], 'r', self.data_mensagem[i], [x + 0.25*x for x in tempLim], 'b', self.data_mensagem[i], [x - 0.25*x for x in tempLim], 'b', linewidth=1.0)
plt.plot(self.data_mensagem[i], self.valor[i], 'r', linewidth=1.0)
plt.grid(True)
canvas = FigureCanvasTkAgg(fig, master=self.mainContainerPressao)
plot_widget = canvas.get_tk_widget().pack(side='top', fill='both', expand='true')
fig = plt.figure(2)
for i in range(7, 8): # adiciona os gráficos no vetor
plt.title(str(self.descricao[i]), fontsize=11)
tempLim = savgol_filter(self.valor[i], 27, 2) # aplica o filtro de Savitzky-Golay
plt.plot(self.data_mensagem[i], self.valor[i], 'r', linewidth=1.0)
plt.grid(True)
canvas = FigureCanvasTkAgg(fig, master=self.mainContainerCondutancia)
plot_widget = canvas.get_tk_widget().pack(side='top', fill='both', expand='true')
# Método para conexão com o banco de dados
def updateplot(self, ellipsoid, title=None, **kwargs):
if ellipsoid is None:
self.figure = matplotlib.figure.Figure()
self.canvas = FigureCanvasTkAgg(self.figure, master=self.parent)
self.canvas.show()
else:
self.figure.clf()
ellipsoid.plotsummary(figure=self.figure, title=title, pointcolor=kwargs.get('pointcolor', 'r'))
#self.figure.canvas.draw()
self.canvas.show()
def __init__(self, master, figsize=(9, 6)):
tk.Frame.__init__(self, master)
self.figure = Figure(figsize=figsize)
self.canvas = FigureCanvasTkAgg(self.figure, master=self)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
self.toolbar = NavigationToolbar2TkAgg(self.canvas, self)
self.toolbar.update()
LoanMortgageCalculatorGUI.py 文件源码
项目:Miniprojects
作者: Ivy-Coding-Camp
项目源码
文件源码
阅读 15
收藏 0
点赞 0
评论 0
def __init__(self, parent, controller, number_of_months, balances, interests, principals):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Mortgage Visualization", font=LARGE_FONT)
label.pack(pady=10,padx=10)
Button(self, text="Back", command=lambda: controller.show_frame(InputPage)).pack()
months = list()
i = 1
while i <= number_of_months:
months.append(i)
i = i + 1
f = Figure()
f.subplots_adjust(left=0.15, right=0.95, wspace=0.25, hspace=0.75)
a = f.add_subplot(211)
plot1, = a.plot(months, interests,'r')
plot2, = a.plot(months, principals,'g')
b = f.add_subplot(212)
plot3 = b.plot(months, balances, 'b')
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def plot (self, filepath):
if self.prediction is not None:
self.prediction.destroy()
if self.canvas is not None:
self.canvas.destroy()
fig = msp(filepath)
canvas = FigureCanvasTkAgg(fig, master=self.root)
self.canvas = canvas.get_tk_widget()
self.canvas.grid(row=0, column=0)
canvas.draw()
def __init__(self, master):
frame = Frame(master)
frame.pack()
Label(frame, text="PM 2.5: ").grid(row=0, columnspan=2)
Label(frame, text="µg/m^3: ").grid(row=0, column=3)
Label(frame, text="PM 10: ").grid(row=1, columnspan=2)
Label(frame, text="µg/m^3: ").grid(row=1, column=3)
self.result_pm25 = DoubleVar()
Label(frame, textvariable=self.result_pm25).grid(row=0, column=2)
self.result_pm10 = DoubleVar()
Label(frame, textvariable=self.result_pm10).grid(row=1, column=2)
button0 = Button(frame, text="Start", command=self.sensor_wake)
button0.grid(row=2, column=0)
button1 = Button(frame, text="Stop", command=self.sensor_sleep)
button1.grid(row=2, column=1)
button2 = Button(frame, text="Read", command=self.sensor_read)
button2.grid(row=2, column=2)
button3 = Button(frame, text="Record", command=self.sensor_live)
button3.grid(row=2, column=3)
button4 = Button(frame, text="Quit", command=self.quit)
button4.grid(row=2, column=4)
#Label(frame, text="").grid(row=3, column=3)
fig = pylab.Figure()
self.canvas = FigureCanvasTkAgg(fig, master=master)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
self.ax = fig.add_subplot(111)
self.ax.grid(True)
self.ax.set_title("PM2.5 and PM10")
self.ax.set_xlabel("Time (seconds)")
self.ax.set_ylabel("PM (ug/m^3)")
self.ax.axis([0,300,0,60])
# 0xAA, 0xB4, 0x06, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x06, 0xAB