Обновить график на основе выбора с помощью PysimpleGui - PullRequest
0 голосов
/ 09 июля 2020

Я пытаюсь сделать следующее: у меня есть фрейм, который я очистил, чтобы отобразить некоторые данные. Этот новый фрейм имеет 9 столбцов, один столбец с именем «Цикл», четыре столбца для temp [temp1, temp2, temp3, temp4] и четыре столбца для давления [p1, p2, p3, p4]. Я хотел бы достичь следующего.

Создайте небольшой GUI (точнее, .exe), где пользователь может выбрать конкретный c номер цикла, и на основе выбора он получит цифру в том числе 4 участка. t1 / p1, t2p2, t3, p3, t4 / p4. Мне удалось получить желаемый результат, если я запустил GUI через spyder, т.е. я могу выбрать, например, цикл 1 и получить первый график. Затем я выбираю цикл 10 и получаю следующий сюжет. Однако, если я создаю .exe с помощью pyinstaller, если я выбираю цикл в первый раз, я получаю первый график, но теперь, если я выбираю другой цикл, я не получаю новый график. Просто ничего не происходит.

Я был бы очень рад, если бы мне помогли

import PySimpleGUI as sg
import matplotlib.pyplot as plt
import pandas as pd
excel_path=sg.PopupGetFile("Select CSV file",title="Temperature / Pressure Plots")
df=pd.read_csv(str(excel_path),sep=";")
df.drop(df.columns[df.columns.str.contains("Unnamed")],1,inplace=True)
liste_cycle_number=list(df["CycleNr"].unique())
    
layout=[[
    sg.Text("Cycle Number",size=(20,1),justification="left"),sg.DropDown(values=liste_cycle_number,size=(10,1),key="Liste")],
    [sg.Button('Show'), sg.Button('Exit')]]
    
window = sg.Window('Window that stays open', 
while True:
    def plotting():
        def make_format(current, other):
            # current and other are axes
            def format_coord(x, y):
                # x, y are data coordinates
                # convert to display coords
                display_coord = current.transData.transform((x,y))
                inv = other.transData.inverted()
                # convert back to data coords with respect to ax
                ax_coord = inv.transform(display_coord)
                coords = [ax_coord, (x, y)]
                return ('Left: {:<40}    Right: {:<}'
                            .format(*['({:.3f}, {:.3f})'.format(x, y) for x,y in coords]))
            return format_coord    
            
            
        fig,ax=plt.subplots(2,2,sharex=True)
        fig.suptitle("Temperature / Pressure Curves for Cycle-Number"+" "+str(values["Liste"]), fontsize=16)
            
        pl1_1=ax[0,0].plot(filtered_df.index,filtered_df["eBar1"], 'r-',label="eBar1")
        ax2=ax[0,0].twinx()
        ax2.format_coord = make_format(ax2, ax[0,0])
        pl1_2=ax2.plot(filtered_df.index,filtered_df["eCelcius1"], 'g-',label="eCelcius1")
        plots1_1=pl1_1+pl1_2
        legends_1=[l.get_label() for l in plots1_1]
        ax[0,0].legend(plots1_1,legends_1,loc="best")
            
        pl2_1=ax[0,1].plot(filtered_df.index,filtered_df["eBar2"], 'r-',label="eBar2")
        ax2_2=ax[0,1].twinx()
        ax2_2.format_coord=make_format(ax2_2,ax[0,1])
        pl2_2=ax2_2.plot(filtered_df.index,filtered_df["eCelcius2"], 'g-',label="eCelcius2")
        plots2_2=pl2_1+pl2_2
        legends_2=[l.get_label() for l in plots2_2]     
        ax[0,1].legend(plots2_2,legends_2,loc="best")
            
        pl3_1=ax[1,0].plot(filtered_df.index,filtered_df["eBar3"], 'r-',label="eBar3")
        ax3_2=ax[1,0].twinx()
        ax3_2.format_coord=make_format(ax3_2,ax[1,0])
        pl3_2=ax3_2.plot(filtered_df.index,filtered_df["eCelcius3"], 'g-',label="eCelcius3")
        plots3_2=pl3_1+pl3_2
        legends_3=[l.get_label() for l in plots3_2]
        ax[1,0].legend(plots3_2,legends_3,loc="best")
            
        pl4_1=ax[1,1].plot(filtered_df.index,filtered_df["eBar4"], 'r-',label="eBar4")
        ax4_2=ax[1,1].twinx()
        ax4_2.format_coord=make_format(ax4_2,ax[1,1])
        pl4_2=ax4_2.plot(filtered_df.index,filtered_df["eCelcius4"], 'g-',label="eCelcius4")
        plots4_2=pl4_1+pl4_2
            
        legends_4=[l4.get_label() for l4 in plots4_2]
        ax[1,1].legend(plots4_2,legends_4,loc="best")
        plt.show()    
        
    event, values = window.read()
    filtered_df=df.loc[df["CycleNr"]==values["Liste"]]
    time=filtered_df.columns[13:].values.astype(float)
    usecols=filtered_df.columns[12:]
    filtered_df=filtered_df[usecols].T
    new_columns=["eBar1","eCelcius1","eBar2","eCelcius2",
              "eBar3","eCelcius3",
              "eBar4","eCelcius4"]
    filtered_df.columns=new_columns
    filtered_df=filtered_df.iloc[1:]
    filtered_df = filtered_df.apply(pd.to_numeric, errors='coerce')
    filtered_df.index=pd.to_numeric(filtered_df.index)
    # print(filtered_df)
    if event == None or event == 'Exit':
        break
    if event=="Show":
        plotting()
  
window.close()
...