我正在尝试我的第一个Tkinter应用程序,但是在绘制时遇到了一些麻烦。
这是我的代码:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.21
# in conjunction with Tcl version 8.6
# Mar 27, 2019 12:16:17 PM CET platform: Windows NT
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
#import test_support
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.decomposition import PCA
import matplotlib.backends.tkagg as tkagg
from matplotlib.backends.backend_agg import FigureCanvasAgg
class Aplicacion:
def __init__(self):
self.top = tk.Tk()
self.top.geometry("600x270+422+130")
self.top.title("New Toplevel")
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.top.configure(background="#d9d9d9")
self.Label1 = tk.Label(self.top)
self.Label1.place(relx=0.067, rely=0.148, height=31, width=164)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''Selecciona el model a utilitzar:''')
self.Label1.configure(width=164)
self.var = IntVar()
self.Radiobutton1 = tk.Radiobutton(self.top)
self.Radiobutton1.place(relx=0.117, rely=0.296, relheight=0.093
, relwidth=0.088)
self.Radiobutton1.configure(activebackground="#ececec")
self.Radiobutton1.configure(activeforeground="#000000")
self.Radiobutton1.configure(background="#d9d9d9")
self.Radiobutton1.configure(disabledforeground="#a3a3a3")
self.Radiobutton1.configure(foreground="#000000")
self.Radiobutton1.configure(highlightbackground="#d9d9d9")
self.Radiobutton1.configure(highlightcolor="black")
self.Radiobutton1.configure(justify='left')
self.Radiobutton1.configure(text='''KNN''')
self.Radiobutton1.configure(variable=self.var)
self.Radiobutton1.configure(value=1)
self.Radiobutton2 = tk.Radiobutton(self.top)
self.Radiobutton2.place(relx=0.117, rely=0.407, relheight=0.093
, relwidth=0.155)
self.Radiobutton2.configure(activebackground="#ececec")
self.Radiobutton2.configure(activeforeground="#000000")
self.Radiobutton2.configure(background="#d9d9d9")
self.Radiobutton2.configure(cursor="fleur")
self.Radiobutton2.configure(disabledforeground="#a3a3a3")
self.Radiobutton2.configure(foreground="#000000")
self.Radiobutton2.configure(highlightbackground="#d9d9d9")
self.Radiobutton2.configure(highlightcolor="black")
self.Radiobutton2.configure(justify='left')
self.Radiobutton2.configure(text='''LinealModel''')
self.Radiobutton2.configure(variable=self.var)
self.Radiobutton2.configure(value=2)
self.Button1 = tk.Button(self.top)
self.Button1.place(relx=0.117, rely=0.667, height=24, width=112)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Mostra la predicció''')
self.Button1.configure(command=self.plot_prediction)
self.Canvas1 = tk.Canvas(self.top)
self.Canvas1.place(relx=0.35, rely=0.259, relheight=0.456, relwidth=0.305)
self.Canvas1.configure(background="#d9d9d9")
self.Canvas1.configure(borderwidth="2")
self.Canvas1.configure(insertbackground="black")
self.Canvas1.configure(relief='ridge')
self.Canvas1.configure(selectbackground="#c4c4c4")
self.Canvas1.configure(selectforeground="black")
self.Canvas1.configure(width=183)
self.Canvas2 = tk.Canvas(self.top)
self.Canvas2.place(relx=0.667, rely=0.259, relheight=0.456, relwidth=0.305)
self.Canvas2.configure(background="#d9d9d9")
self.Canvas2.configure(borderwidth="2")
self.Canvas2.configure(insertbackground="black")
self.Canvas2.configure(relief='ridge')
self.Canvas2.configure(selectbackground="#c4c4c4")
self.Canvas2.configure(selectforeground="black")
self.Canvas2.configure(width=183)
def get_iris_dataset(self):
# Obte un dataset en format X_train, y_train, X_test, y_test
iris = datasets.load_iris()
self.X = iris.data
self.target_names = iris.target_names
self.y = iris.target
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
self.X, self.y, test_size=0.33, random_state=42)
def plot_prediction(self):
self.get_iris_dataset()
if self.var.get() == 1:
algoritmo = LogisticRegression()
elif self.var.get() == 2:
algoritmo = KNeighborsClassifier()
algoritmo.fit(self.X, self.y)
self.Y_pred = algoritmo.predict(self.X)
print('Precisión: {}'.format(algoritmo.score(self.X, self.y)))
self.plot_pca(self.y,self.Canvas1)
self.plot_pca(self.Y_pred, self.Canvas2)
def plot_pca(self, y, canvas):
pca = PCA(n_components=2)
X_r = pca.fit(self.X).transform(self.X)
mplot = plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2
for color, i, target_name in zip(colors, [0, 1, 2], self.target_names):
plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
label=target_name, figure = mplot)
mplot.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of prediction of IRIS dataset', figure = mplot)
# self.draw_figure(canvas, mplot)
return(mplot)
def draw_figure(canvas, figure, loc=(0, 0)):
""" Draw a matplotlib figure onto a Tk canvas
loc: location of top-left corner of figure on canvas in pixels.
Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
"""
figure_canvas_agg = FigureCanvasAgg(figure)
figure_canvas_agg.draw()
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
figure_w, figure_h = int(figure_w), int(figure_h)
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
# Position: convert from top-left anchor to center anchor
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
# Unfortunately, there's no accessor for the pointer to the native renderer
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
# Return a handle which contains a reference to the photo object
# which must be kept live or else the picture disappears
return photo
def run(self):
# Funcio a cridar per executar laplicacio
self.top.mainloop()
if __name__ == '__main__':
# vp_start_gui()
mi_app = Aplicacion()
mi_app.run()
如您所见,使用这两行“ self.plot_pca(self.y,self.Canvas1); self.plot_pca(self.Y_pred,self.Canvas2)“我想用实际数据绘制PCA,并用预测绘制PCA。 问题是,似乎我无法在画布上存储matplotlib.pyplot.figure,而是必须使用matplotlib.figure.Figure对象。有什么办法可以将我的绘图存储到Canvas对象中以在应用程序中显示?
非常感谢!
Xevi