Показать изображение pyplot на холсте - PullRequest
0 голосов
/ 11 июля 2020

Я начинаю работать над приложением tkinter и хочу показать созданную мной радарную диаграмму. Я искал на форуме и на других сайтах, но не могу понять, как это работает. Я могу создавать новые изображения из файлов, но не из сюжета ... Я не знаю, как показать это на холсте ... Кто-нибудь может мне помочь ?? Вот весь код:

import tkinter as tk
from tkinter import *
import os
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from scipy.spatial import distance
from PIL import Image,ImageTk
from math import pi
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)

root = tk.Tk()
#root = tk.Toplevel()

nombres = []
parecidos_razonables = []

nba = pd.read_excel("/Users/Rodrigo/Desktop/NBA.xlsx")
euroliga = pd.read_excel("/Users/Rodrigo/Desktop/EUROLIGA.xlsx")

photos2 = 88

def seleccionar_jugador():



for widget in frame1.winfo_children():
    widget.destroy()
    
canvas.create_rectangle(400, 95, 675, 325, outline="#263D42", fill="#263D42")

   
        
nombre = entrada_datos.get()
nombres.append(nombre)

label = tk.Label(frame1 , text=nombres[-1], bg="red")
label.pack()
'''
for x in nombres:
    label = tk.Label(frame1 , text=x, bg="red")
    label.pack()
    
'''
for widget in frame2.winfo_children():
    widget.destroy()
    
photo1 = "/Users/Rodrigo/Desktop/app/imagenes/"
photo2 = ".png"

photo_path = photo1 + nombres[-1] + photo2
img = Image.open(photo_path)
photo = ImageTk.PhotoImage(img)


canvas.photo = photo
canvas.create_image(180, 200, image=photo)






def similar_player():



euroliga_triunfa = euroliga[(euroliga['TRIUNFAN VS NBA PLAYERS'] == 'SI')]
euroliga_triunfa_2 = euroliga_triunfa.drop(columns=['TRIUNFAN ENTRE EUROLIGUERS'])
euroliga_triunfa_3 = euroliga_triunfa_2.rename(columns={"TRIUNFAN VS NBA PLAYERS": "TRIUNFA"})
euroliga_triunfa_3["NAME"] = euroliga_triunfa_3["NAME"] + "*"
nba_triunfa = nba[(nba['TRIUNFA'] == 'SI')]
df_final = pd.concat([nba_triunfa, euroliga_triunfa_3])
target_columns = ["MPG", "2PPER", "3PPER", "FTPER", "PPG", "RPG", "APG", "SPG", "BPG"]
distance_data = df_final[target_columns]
jugador = nombres[-1]
jugador_stats = df_final[df_final["NAME"] == jugador].iloc[0]
df_final_normalizada = (distance_data - distance_data.mean()) / distance_data.std()
jugador_nomalizado = df_final_normalizada[df_final["NAME"] == jugador]
distancias_euclidea = df_final_normalizada.apply(lambda row:
                                               distance. euclidean(row, jugador_nomalizado), axis=1)

df_distancias = pd.DataFrame(data={"dist": distancias_euclidea, "idx": distancias_euclidea.index, "NAME": df_final["NAME"]})
df_distancias.sort_values("dist", inplace=True)
distancia_corta = df_distancias.iloc[1]["idx"]
parecido_razonable = df_final.loc[int(distancia_corta)]["NAME"]
parecidos_razonables.append(parecido_razonable)
label_2 = tk.Label(frame2, text=parecido_razonable, bg="green")
label_2.pack()



photo3 = "/Users/Rodrigo/Desktop/app/imagenes/"
photo4 = ".png"

photo_path2 = photo3 + parecido_razonable + photo4
img2 = Image.open(photo_path2)
photo2 = ImageTk.PhotoImage(img2)


canvas.photo2 = photo2
canvas.create_image(530, 200, image=photo2)

def radar():

#PRIMER JUGADOR

euroliga_triunfa = euroliga[(euroliga['TRIUNFAN VS NBA PLAYERS'] == 'SI')]
euroliga_triunfa_2 = euroliga_triunfa.drop(columns=['TRIUNFAN ENTRE EUROLIGUERS'])
euroliga_triunfa_3 = euroliga_triunfa_2.rename(columns={"TRIUNFAN VS NBA PLAYERS": "TRIUNFA"})
euroliga_triunfa_3["NAME"] = euroliga_triunfa_3["NAME"] + "*"
nba_triunfa = nba[(nba['TRIUNFA'] == 'SI')]
df_final = pd.concat([nba_triunfa, euroliga_triunfa_3])
target_columns = ["MPG", "2PPER", "3PPER", "FTPER", "PPG", "RPG", "APG", "SPG", "BPG"]
distance_data = df_final[target_columns]
jugador = nombres[-1]
#print(nombres[-1])
jugador_stats = df_final[df_final["NAME"] == jugador].iloc[0]
#print(jugador_stats)
df_final_normalizada = (distance_data - distance_data.mean()) / distance_data.std()
jugador_nomalizado = df_final_normalizada[df_final["NAME"] == jugador]
distancias_euclidea = df_final_normalizada.apply(lambda row:
                                               distance. euclidean(row, jugador_nomalizado), axis=1)
data = df_final_normalizada
df_final_normalizada.describe()


data_2 = data.transform(lambda x: (x+3.859334)*10.5349944069715)


df_distancias = pd.DataFrame(data={"NAME": df_final["NAME"],
                                  "MPG": data_2["MPG"],"2PPER": data_2["2PPER"], "3PPER": data_2["3PPER"],
                                  "FTPER": data_2["FTPER"], "PPG": data_2["PPG"], "RPG": data_2["RPG"],
                                  "APG": data_2["APG"], "SPG": data_2["SPG"], "BPG": data_2["BPG"]})





#rint(data_2)
valores = df_distancias.drop(columns=['NAME'])

Attributes =list(valores)
AttNo = len(Attributes)

#values = df_distancias[df_distancias["NAME"] == jugador, parecidos_razonables[-1]]
values = df_distancias[(df_distancias['NAME'] == jugador) | (df_distancias['NAME'] == parecidos_razonables[-1])]
values = values.drop(columns=['NAME'])
values3 = values.iloc[0].tolist()
values3 += values3 [:1]

values2 = values.iloc[1].tolist()
values2 += values2 [:1]


  
angles = [n / float(AttNo) * 2 * pi for n in range(AttNo)]
angles += angles [:1]

angles2 = [n / float(AttNo) * 2 * pi for n in range(AttNo)]
angles2 += angles2 [:1]

ax = plt.subplot(111, polar=True)

#Add the attribute labels to our axes
plt.xticks(angles,Attributes)

#Plot the line around the outside of the filled area, using the angles and values calculated before
ax.plot(angles,values3)

#Fill in the area plotted in the last line
ax.fill(angles, values3, 'teal', alpha=0.1)

ax.plot(angles2,values2)
ax.fill(angles2, values2, 'red', alpha=0.1)


#Give the plot a title and show it
#ax.set_title(nombres[-1])
#plt.title(nombres[-1], y=1.08)
#plt.show()

plt.figtext(0.2,1.1,nombres[-1],color="orange")
plt.figtext(0.2,1.05,"vs")
plt.figtext(0.2,1.0,parecidos_razonables[-1],color="blue")
fig = plt.show()
fig.show()





canvas = tk.Canvas(root, height=700, width=700, bg="#263D42")
canvas.pack()



entrada_datos = tk.Entry(root)
canvas.create_window(150, 50, window=entrada_datos)


frame1 =tk.Frame(root, bg="grey")
frame1.place(relwidth=0.4, relheight=0.02, relx=0.1, rely=0.1)

frame2 =tk.Frame(root, bg="grey")
frame2.place(relwidth=0.3, relheight=0.02, relx=0.6, rely=0.1)


boton2 = tk.Button(root, text="Selecciona Jugador", padx=10, 
               pady=5, fg="white", bg="#263D42", command=seleccionar_jugador)
boton2.pack()

boton1 = tk.Button(root, text="Buscar Parecido", padx=10, 
               pady=5, fg="white", bg="#263D42", command=similar_player)

boton1.pack()

boton3 = tk.Button(root, text="Gráfica 1", padx=10, 
               pady=5, fg="white", bg="#263D42", anchor=E, command=radar)
boton3.pack()


root.mainloop()

Заранее спасибо !!

...