rsj0315 发表于 2021-1-21 15:50:13

打包exe后,启动速度慢的问题




废话不多说上源码,两个py文件,第一个叫database。如下:
import pyodbc
import pandas as pd
import os
import tempfile
os.environ['MPLCONFIGDIR']=tempfile.mkdtemp()
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import warnings
warnings.filterwarnings('ignore')
import datetime
import concurrent.futures
import time

now = datetime.datetime.now().strftime('%Y-%m-%d')
now_15ago=(datetime.datetime.now()-datetime.timedelta(days=14)).strftime('%Y-%m-%d')
now_1ago=(datetime.datetime.now()-datetime.timedelta(days=1)).strftime('%Y-%m-%d')
now_2ago=(datetime.datetime.now()-datetime.timedelta(days=2)).strftime('%Y-%m-%d')
now_30ago = (datetime.datetime.now()-datetime.timedelta(days=30)).strftime('%Y-%m-%d')

plt.rcParams['font.sans-serif'] = ['STZhongsong']# 中文字体设置-黑体
plt.rcParams['axes.unicode_minus'] = False# 解决保存图像是负号'-'显示为方块的问题
#显示所有列
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#下边是5条产线,15个access数据库表格
a_fg = r'A Rubber Line POs List.mdb'
a_per = r'A Rubber Line Performance List.mdb'
a_stop = r'A Rubber Line Stops List.mdb'

b_fg = r'B Rubber Line POs List.mdb'
b_per = r'B Rubber Line Performance List.mdb'
b_stop = r'B Rubber Line Stops List.mdb'

c_fg = r'C Rubber Line POs List.mdb'
c_per = r'C Rubber Line Performance List.mdb'
c_stop = r'C Rubber Line Stops List.mdb'

cb_fg = r'CB Rubber Line POs List.mdb'
cb_per = r'CB Rubber Line Performance List.mdb'
cb_stop = r‘CB Rubber Line Stops List.mdb'

ccv_fg = r'CCV XLPE Line POs List.mdb'
ccv_per = r'CCV XLPE Line Performance List.mdb'
ccv_stop = r'CCV XLPE Line Stops List.mdb'

#下边是后边要用的sql语句
fg_a = "SELECT * FROM A_Rubber_Line_POLIST"
per_a = "SELECT * FROM A_Rubber_Line_PerformList"
stop_a = "SELECT * FROM A_Rubber_Line_StopList"

fg_b = "SELECT * FROM B_Rubber_Line_POLIST"
per_b = "SELECT * FROM B_Rubber_Line_PerformList"
stop_b = "SELECT * FROM B_Rubber_Line_StopList"

fg_c = "SELECT * FROM C_Rubber_Line_POLIST"
per_c = "SELECT * FROM C_Rubber_Line_PerformList"
stop_c = "SELECT * FROM C_Rubber_Line_StopList"

fg_cb = "SELECT * FROM CB_Rubber_Line_POLIST"
per_cb = "SELECT * FROM CB_Rubber_Line_PerformList"
stop_cb = "SELECT * FROM CB_Rubber_Line_StopList"

fg_ccv = "SELECT * FROM CCV_XLPE_Line_POLIST"
per_ccv = "SELECT * FROM CCV_XLPE_Line_PerformList"
stop_ccv = "SELECT * FROM CCV_XLPE_Line_StopList"



savepath = r'C:\DATA_FILE'
#下边这个函数是为了让饼图显示数量和百分比的
def my_label(pct, allvals):
    try:
      absolute = int(pct/100.*np.sum(allvals))
      return "{:.1f}%\n({:d})".format(pct, absolute)
    except Exception as e:
      print(e)
#下边这个函数是读取5个fg数据库表格的通用函数,5个表格字段一样的
def get_data_fg(mdb_file,sql,line):
    global savepath
    driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
    con = pyodbc.connect(f'Driver={driver};DBQ={mdb_file};Pwd=FSL24680')
    df = pd.read_sql(sql,con)
    df['PRODUCTION_DATE'] = df['COIL_NO'].str[:8]
    df['PRODUCTION_DATE'] = pd.to_datetime(df['PRODUCTION_DATE'], format='%Y-%m-%d')
    df['date'] = df['PRODUCTION_DATE']
    # df.set_index('date', inplace=True)
    df['line'] = line
    df['itp_'] = df['QUALITY_DECISION'].str.cat(df['PRODUCTION_DECISION'], na_rep='_')# 连接合并,空的写下划线
    df['itp'] = df['itp_'].isin(['Failnan', 'nanFail', 'FailFail', 'FailPass', 'PassFail'])# 只要含有Fail的就认为是不合格轴
    df['itp'] = df['itp'].astype('str')# 把判定结果的转换为字符串,False代表合格。

    df['段长'] = pd.cut(df['COIL_LENGTH'],
                           bins=,
                           include_lowest=True,
                           labels=['300m以内', '300到600m', '600到1000m', '1km以上'])
    # print(df)
    # print(df.info())
    df.to_pickle(os.path.join(savepath, f'{line}fg.pkl'))
    # df.to_excel(os.path.join(savepath, f'{line}fg.xlsx'))
    print('***********',sql,"****************")
    return df
##下边这个函数是读取5个per数据库表格的通用函数,5个表格字段一样的
def get_data_per(mdb_file,sql,line):
    global savepath
    driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
    con = pyodbc.connect(f'Driver={driver};DBQ={mdb_file};Pwd=FSL24680')
    df = pd.read_sql(sql,con)
    df['date'] = df['PRODUCTION_DATE']
    # df.set_index('date', inplace=True)
    df['line'] = line
    df.to_pickle(os.path.join(savepath, f'{line}per.pkl'))
    # df.to_excel(os.path.join(savepath, f'{line}per.xlsx'))
    print('***********',sql,"****************")
    return df
#下边这个函数是读取5个stop数据库表格的通用函数,5个表格字段一样的
def get_data_stop(mdb_file,sql,line):
    global savepath
    driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
    con = pyodbc.connect(f'Driver={driver};DBQ={mdb_file};Pwd=FSL24680')
    df = pd.read_sql(sql,con)
    # print(df)
    df['STOP_REASON'] = np.where((df['STOP_TIME_HOUR'] > 10) & (df['STOP_REASON'] == ''), '歇班',
                                    df['STOP_REASON'])
    df['STOP_REASON'] = np.where((df['STOP_TIME_HOUR'] < 10) & (df['STOP_REASON'] == ''), '等待下班',
                                    df['STOP_REASON'])
    df_stop = df[~df['STOP_REASON'].astype(str).str.contains('歇班')]
    # print(df_stop)
    a = df_stop.values.tolist()
    # print('---')
    # print(a)
    res = []
    res_=[]
    for i in range(0, len(a) - 1):
      m = a
      n = a
      b = (m - n).total_seconds() / 3600
      if b >= 0.2:
            res.append(a)
      else:
            res.append(, a, a, a, a, a,a,a,a])
            res_.append(
                , a, a, a, a, a + '+跨班', a, a, a])
    df_stop2 = pd.DataFrame(res)
    print(df_stop2)
    df_stop2.columns = ['date', 'INDEX SUB_INDEX', 'STOP_FROM', 'STOP_TO', 'STOP_TIME_HOUR', 'STOP_REASON',
                        'PRODUCTION_DATE', 'SHIFT', 'OPERATOR','LINE']
    df_stop2.drop_duplicates(subset=['STOP_TO'], keep='first', inplace=True)
    df_stop2['date']=df_stop2['PRODUCTION_DATE']
    # df_stop2.set_index('date', inplace=True)
    df_stop2['line'] = line
    # print(df_stop2)
    df_stop2.to_pickle(os.path.join(savepath, f'{line}stop.pkl'))
    # df_stop2.to_excel(os.path.join(savepath, f'{line}stop.xlsx'))

    if len(res_)==9:
      df_stop3 = pd.DataFrame(res_)
      df_stop3.columns = ['date', 'INDEX SUB_INDEX', 'STOP_FROM', 'STOP_TO', 'STOP_TIME_HOUR', 'STOP_REASON',
                            'PRODUCTION_DATE', 'SHIFT', 'OPERATOR']
      df_stop3.drop_duplicates(subset=['STOP_TO'], keep='first', inplace=True)
      df_stop3['date'] = df_stop3['PRODUCTION_DATE']
      df_stop3['line'] = line
      # df_stop3.to_excel(os.path.join(savepath, f'{line}stop_跨班.xlsx'))
    print('***********',sql,"****************")
    return df_stop2
#把5个fg表格合并成一个并输出pkl文件
def concat_file_fg():
    start = time.time()
    with concurrent.futures.ThreadPoolExecutor() as executor:
      fga = executor.submit(get_data_fg, a_fg, fg_a, 'A')
      fgb = executor.submit(get_data_fg, b_fg, fg_b, 'B')
      fgc = executor.submit(get_data_fg, c_fg, fg_c, 'C')
      fgcb = executor.submit(get_data_fg, cb_fg, fg_cb, 'CB')
      fgccv = executor.submit(get_data_fg,ccv_fg, fg_ccv, 'CCV')
      dfga = fga.result()
      dfgb = fgb.result()
      dfgc = fgc.result()
      dfgcb = fgcb.result()
      dfgccv = fgccv.result()
      df_fg = pd.concat()
      df_fg.to_excel(r'C:\PTCC_MES_DATA_FILE\fg2021_all.xlsx', index=False)
      df_fg.to_pickle(r'C:\PTCC_MES_DATA_FILE\fg2021_all.pkl')
    end = time.time()
    print(end-start)
    print('fg载入数据完成------------------')
    return df_fg
#把5个per表格合并成一个并输出pkl文件
def concat_file_per():
    start = time.time()
    with concurrent.futures.ThreadPoolExecutor() as executor:
      pera = executor.submit(get_data_per, a_per, per_a, 'A')
      perb = executor.submit(get_data_per, b_per, per_b, 'B')
      perc = executor.submit(get_data_per, c_per, per_c, 'C')
      percb = executor.submit(get_data_per, cb_per, per_cb, 'CB')
      perccv = executor.submit(get_data_per, ccv_per, per_ccv, 'CCV')
      dfpa = pera.result()
      dfpb = perb.result()
      dfpc = perc.result()
      dfpcb = percb.result()
      dfpccv = perccv.result()
      df_p = pd.concat()
      df_p.to_excel(r'C:\PTCC_MES_DATA_FILE\per2021_all.xlsx', index=False)
      df_p.to_pickle(r'C:\PTCC_MES_DATA_FILE\per2021_all.pkl')
    end = time.time()
    print(end - start)
    print('per载入数据完成------------------')
    return df_p
#把5个stop表格合并成一个并输出pkl文件
def concat_file_stop():
    start = time.time()
    with concurrent.futures.ThreadPoolExecutor() as executor:
      stopa = executor.submit(get_data_stop, a_stop, stop_a, 'A')
      stopb = executor.submit(get_data_stop, b_stop, stop_b, 'B')
      stopc = executor.submit(get_data_stop, c_stop, stop_c, 'C')
      stopcb = executor.submit(get_data_stop, cb_stop, stop_cb, 'CB')
      stopccv = executor.submit(get_data_stop, ccv_stop, stop_ccv, 'CCV')
      dfsa = stopa.result()
      dfsb = stopb.result()
      dfsc = stopc.result()
      dfscb = stopcb.result()
      dfsccv = stopccv.result()
      df_s = pd.concat()
      df_s.to_excel(r'C:\PTCC_MES_DATA_FILE\stop2021_all.xlsx', index=False)
      df_s.to_pickle(r'C:\PTCC_MES_DATA_FILE\stop2021_all.pkl')
    end = time.time()
    print(end - start)
    print('stop载入数据完成------------------')
    return df_s
#画图函数1,ui上点击按钮对应画图
def out1_data(line,start=now_15ago,end=now,now_1 = now_1ago):

    global savepath
    df_fg = pd.read_pickle(os.path.join(savepath, f'{line}fg.pkl'))
    df_fg.set_index('date', inplace=True)
    df_fg = df_fg.loc
    df_fg['PRODUCTION_DATE'] = df_fg['PRODUCTION_DATE'].astype(str).str[:10]
    # print(df_fg)

    # df_per = pd.read_excel(os.path.join(savepath, f'{line}per.xlsx'))
    df_per = pd.read_pickle(os.path.join(savepath, f'{line}per.pkl'))
    df_per.set_index('date', inplace=True)
    df_per = df_per.loc
    df_per['PRODUCTION_DATE']=df_per['PRODUCTION_DATE'].astype(str).str[:10]
    # print(df_per)

    df_stop = pd.read_pickle((os.path.join(savepath, f'{line}stop.pkl')))
    df_stop['PRODUCTION_DATE'] = df_stop['PRODUCTION_DATE'].astype(str).str[:10]
    df_stop.set_index('date', inplace=True)


    #----------------------------------------------------
    plt.figure(facecolor='white', figsize=(16, 9))
    sns.set(style="darkgrid")
    plt.rcParams['font.sans-serif'] = ['STZhongsong']# 中文字体设置-黑体
    plt.rcParams['axes.unicode_minus'] = False# 解决保存图像是负号'-'显示为方块的问题
    try:
      ax1 = plt.subplot(221)
      sns.lineplot(x='PRODUCTION_DATE',
                   y='SPEED_EFFICIENCY',
                   data=df_per,
                   hue='SHIFT',
                  marker='*',
                   ax=ax1)
      for x,y in zip(df_per['PRODUCTION_DATE'],df_per['SPEED_EFFICIENCY']):
            if y<0.95:
                plt.text(x=x,y=y+0.02,s='%.01f%%' % (y * 100),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      plt.ylim(0, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      # plt.grid(axis='y',linestyle='--',color='red',alpha=0.3)
      plt.ylabel('速度效率 / %', fontsize=14, fontweight='bold')
      ax1.set_title(f'{line} Line 15天 速度效率 %\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 速度效率')

    ax2 = plt.subplot(222)
    try:
      zongshu = df_fg.groupby(['PRODUCTION_DATE', 'PRODUCTION_SHIFT'], as_index=False)['itp'].agg('count')
      df_fg_hege = df_fg == 'False']
      hegeshu = df_fg_hege.groupby(['PRODUCTION_DATE','PRODUCTION_SHIFT'],as_index=False)['itp'].agg('count')
      df_ftq = pd.concat(,axis=1)
      df_ftq.columns = ['PRODUCTION_DATE','PRODUCTION_SHIFT','zongshu','date','SHIFT','hegeshu']
      df_ftq['FTQ']=df_ftq['hegeshu']/df_ftq['zongshu']
      # print(df_ftq)
      sns.lineplot(x='PRODUCTION_DATE',
                     y='FTQ',
                     data=df_ftq,
                     hue='SHIFT',
                     marker='*',
                     ax=ax2)
      for x,y in zip(df_ftq['PRODUCTION_DATE'],df_ftq['FTQ']):
            if y<0.1:
                plt.text(x=x,y=y+0.02,s='%.01f%%' % (y * 100),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('FTQ / %', fontsize=14, fontweight='bold')
      ax2.set_title(f'{line} Line 15天 FTQ %\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 FTQ')
    ax3 = plt.subplot(223)
    try:
      sns.lineplot(x='PRODUCTION_DATE',
                     y='RUN_TIME_HOUR',
                     data=df_per,
                     hue='SHIFT',
                     marker='*',
                     ax=ax3)
      for x,y in zip(df_per['PRODUCTION_DATE'],df_per['RUN_TIME_HOUR']):
            plt.text(x=x,y=y,s=round(y,1),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('run_time / h', fontsize=14, fontweight='bold')
      ax3.set_title(f'{line} Line 15天 Run_Time h\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 Run_Time')

    ax4 = plt.subplot(224)
    try:
      sns.lineplot(x='PRODUCTION_DATE',
                     y='OEE',
                     data=df_per,
                     hue='SHIFT',
                     marker='*',
                     ax=ax4)
      for x,y in zip(df_per['PRODUCTION_DATE'],df_per['OEE']):
            plt.text(x=x,y=y,s='%.01f%%' % (y * 100),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('OEE / %', fontsize=14, fontweight='bold')
      ax4.set_title(f'{line} Line 15天 OEE %\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 OEE')
    plt.tight_layout()
    plt.show()
    ###################################################
    ###################################################
    plt.figure(facecolor='white', figsize=(16, 9))
    ax1 = plt.subplot(221)
    try:
      ax = sns.barplot(x='PRODUCTION_DATE',
                         y='TOTAL_LENGTH',
                         data=df_per,
                         hue='SHIFT',
                         ci=0,
                         ax=ax1)
      for p in ax.patches:
            height = p.get_height()
            ax.text(x=p.get_x() ,
                  y=height + 2,
                  s='{: .0f}m'.format(height), color='red', size=14)
      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('length / m', fontsize=14, fontweight='bold')
      ax1.set_title(f'{line} Line 15天 产量/ m\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 产量')
    #############################################
    ax2 = plt.subplot(222)
    try:
      df_fg1 = df_fg.loc
      axx = sns.barplot(x='COIL_NO',
                        y='COIL_LENGTH',
                        data=df_fg1,
                        ci=0,
                        color='blue',
                        ax=ax2)
      for p in axx.patches:
            height = p.get_height()
            axx.text(x=p.get_x() + (p.get_width() / 2),
                     y=height,
                     s='{: .0f}m'.format(height), color='red', size=14)
      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('length / m', fontsize=14, fontweight='bold')
      ax2.set_title(f'{line} Line昨天产量/ m\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'昨天产量')
    ##################################
    ax3 = plt.subplot(223)
    try:
      df_stop = df_stop.loc
      axxx = sns.barplot(x='STOP_REASON',
                           y='STOP_TIME_HOUR',
                           data=df_stop,
                           hue='SHIFT',
                           estimator=sum,
                           ci=0,
                           ax=ax3)
      for p in axxx.patches:
            height = p.get_height()
            axxx.text(x=p.get_x() + (p.get_width() / 2),
                      y=height + 0.1,
                      s=f'{round(height,1)}h', color='red', size=14)
      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('小时 / m', fontsize=14, fontweight='bold')
      ax3.set_title(f'{line} Line昨天停车 / h\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'昨天停车')
    ax4 = plt.subplot(224)
    try:
      bing = df_per.groupby('SHIFT')['RUN_TIME_HOUR'].agg('sum').sort_values(ascending=True)
      ax4 = bing.plot(kind='pie',
                        subplots=True,
                        # labels=labels,
                        # explode=(0,0.1,0,0),#突显
                        autopct=lambda x: my_label(x, bing),
                        # autopct='%.1f%%',# 设置百分比格式,保留一位
                        pctdistance=0.8,# 设置百分比与圆心的距离
                        startangle=90,# 设置饼图的开始角度
                        radius=1,# 设置饼图的半径
                        counterclock=True,# 是否逆时针,false是顺时针
                        shadow=False,# 无阴影设置
                        labeldistance=1.1,# 默认1.1
                        # rotatelabels=True# True,标签放线是沿半径方向
                        textprops={'fontsize': 13}
                        )
      plt.axis('scaled')# 'tight''scaled'
      plt.ylabel('')
      plt.xlabel('')
      plt.title('\n15天白夜班开车时间占比\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天白夜班开车时间占比')
    plt.tight_layout()
    plt.show()
    return
#画图函数2,ui上点击按钮对应画图
def out2_data(line,start=now_15ago,end=now):
    '''
    近1个月
    停车分析,
    1.次数柏拉图
    2.时长sum柏拉图
    3.时长mean柱状图图
    top3箱图
    '''
    global savepath
    df_s = pd.read_pickle((os.path.join(savepath, f'{line}stop.pkl')))
    df_s['PRODUCTION_DATE'] = df_s['PRODUCTION_DATE'].astype(str).str[:10]
    df_s.set_index('date', inplace=True)

    # 筛选出近一个月的数据
    df_s = df_s.loc
    # df_s['shichang'].dropna(inplace=True)
    try:
      # 筛选停车原因次数中的top3
      top3list = df_s['STOP_REASON'].value_counts().head(3).index.tolist()
      df_s_top1 = df_s.isin(])]
      title1 = top3list
      df_s_top1_count = df_s_top1.groupby('OPERATOR')['STOP_REASON'].agg('count').sort_values(ascending=False)
      # top2的df
      df_s_top2 = df_s.isin(])]
      title2 = top3list
      df_s_top2_count = df_s_top2.groupby('OPERATOR')['STOP_REASON'].agg('count').sort_values(ascending=False)
      # top3的df
      df_s_top3 = df_s.isin(])]
      title3 = top3list
      df_s_top3_count = df_s_top3.groupby('OPERATOR')['STOP_REASON'].agg('count').sort_values(ascending=False)
    except Exception as e:
      print(e,'停车种类不够三种')

    plt.figure(facecolor='white', figsize=(16, 9))
    sns.set(style="darkgrid")
    plt.rcParams['font.sans-serif'] = ['STZhongsong']# 中文字体设置-黑体
    plt.rcParams['axes.unicode_minus'] = False# 解决保存图像是负号'-'显示为方块的问题
    ax1 = plt.subplot(231)
    try:
      df1 = df_s['STOP_REASON'].value_counts()
      p1 = 1.0 * df1.cumsum() / df1.sum()
      df1.plot(kind='bar', ax=ax1)
      for i, v in enumerate(df1.values):
            a = v.__str__().strip('[,]')
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      plt.ylabel(u"stop_count")
      p1.plot(color='r', secondary_y=True, style='-o', linewidth=0.5, ax=ax1)
      plt.annotate(format(p1, '.2%'), xy=(2, p1), xytext=(2 * 0.9, p1 * 0.9),
                     arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
      plt.ylabel(u'count_rate')
      for tick in ax1.get_xticklabels():
            tick.set_rotation(45)
            tick.set_horizontalalignment('right')
      ax1.set_title(f'{line} Line stop_count\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print('停车次数', e)
    # ---------------------------
    ax2 = plt.subplot(232)
    try:
      df2 = df_s.groupby('STOP_REASON')['STOP_TIME_HOUR'].agg('sum').sort_values(ascending=False)
      # print(df2)
      p2 = 1.0 * df2.cumsum() / df2.sum()
      df2.plot(kind='bar', ax=ax2)
      for i, v in enumerate(df2.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      plt.ylabel(u"stop time_sum")
      p2.plot(color='r', secondary_y=True, style='-o', linewidth=0.5, ax=ax2)
      plt.annotate(format(p2, '.2%'), xy=(2, p2), xytext=(2 * 0.9, p2 * 0.9),
                     arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
      plt.ylabel(u'time_rate')
      ax2.set_xlabel('')
      for tick in ax2.get_xticklabels():
            tick.set_rotation(45)
            tick.set_horizontalalignment('right')
      ax2.set_title(f'{line} Line stop_time/h\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print('停车总时长', e)
    ax3 = plt.subplot(233)
    try:
      df3 = df_s.groupby('STOP_REASON')['STOP_TIME_HOUR'].agg('mean').sort_values(ascending=False)
      df3.plot(kind='bar', ax=ax3)
      for i, v in enumerate(df3.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      ax3.set_xlabel('')
      plt.ylabel(u'stop time_ave/h')
      for tick in ax3.get_xticklabels():
            tick.set_rotation(45)
            tick.set_horizontalalignment('right')
      ax3.set_title(f'{line} Line stop time_ave/h\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print('停车平均时长', e)
    # ------------------------
    ax4 = plt.subplot(234)
    try:
      df_s_top1_median = df_s_top1.groupby('OPERATOR')['STOP_TIME_HOUR'].median()
      list1 = df_s_top1_median.index.tolist()
      ax4 = sns.boxplot(
            x='OPERATOR',
            y='STOP_TIME_HOUR',
            hue='OPERATOR',
            data=df_s_top1,
            order=list1
      )
      df_s_top1_25 = df_s_top1.groupby('OPERATOR')['STOP_TIME_HOUR'].describe()['25%']
      df_s_top1_75 = df_s_top1.groupby('OPERATOR')['STOP_TIME_HOUR'].describe()['75%']
      for i, v in enumerate(df_s_top1_median.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(df_s_top1_25.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(df_s_top1_75.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      ax4.tick_params(axis='x', labelsize=15)
      plt.title(f"TOP1:《{title1}》\n", fontsize=18, fontweight='bold')
      plt.ylabel('')
      plt.xlabel('')
      plt.grid(axis='y', color='red', linestyle=':')
    except Exception as e:
      print(e)
      # -------------------------------------------------------------
    ax5 = plt.subplot(235)
    try:
      df_s_top2_median = df_s_top2.groupby('OPERATOR')['STOP_TIME_HOUR'].median()
      list2 = df_s_top2_median.index.tolist()
      ax5 = sns.boxplot(
            x='OPERATOR',
            y='STOP_TIME_HOUR',
            hue='OPERATOR',
            data=df_s_top2,
            order=list2
      )
      df_s_top2_25 = df_s_top2.groupby('OPERATOR')['STOP_TIME_HOUR'].describe()['25%']
      df_s_top2_75 = df_s_top2.groupby('OPERATOR')['STOP_TIME_HOUR'].describe()['75%']
      for i, v in enumerate(df_s_top2_median.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(df_s_top2_25.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(df_s_top2_75.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      ax5.tick_params(axis='x', labelsize=15)
      plt.title(f"TOP2:《{title2}》\n", fontsize=18, fontweight='bold')
      plt.ylabel('')
      plt.xlabel('')
      plt.grid(axis='y', color='red', linestyle=':')
    except Exception as e:
      print(e)
      # ----------------------------------------------------------
    ax6 = plt.subplot(236)
    try:
      df_s_top3_median = df_s_top3.groupby('OPERATOR')['STOP_TIME_HOUR'].median()
      list3 = df_s_top3_median.index.tolist()
      ax6 = sns.boxplot(
            x='OPERATOR',
            y='STOP_TIME_HOUR',
            hue='OPERATOR',
            data=df_s_top3,
            order=list3)
      df_s_top3_25 = df_s_top3.groupby('OPERATOR')['STOP_TIME_HOUR'].describe()['25%']
      df_s_top3_75 = df_s_top3.groupby('OPERATOR')['STOP_TIME_HOUR'].describe()['75%']
      for i, v in enumerate(df_s_top3_median.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(df_s_top3_25.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(df_s_top3_75.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      ax6.tick_params(axis='x', labelsize=15)
      plt.title(f"TOP3:《{title3}》\n", fontsize=18, fontweight='bold')
      plt.ylabel('')
      plt.xlabel('')
      plt.grid(axis='y', color='red', linestyle=':')
    except Exception as e:
      print(e)
    plt.tight_layout()
    plt.show()
    return
#画图函数3,ui上点击按钮对应画图
def out3_data(line,start=now_15ago,end=now):
    '''
    按钮三种的数据都是默认筛选近15天的数据
    1.段长饼图----》fg
    2.run time饼图/人之间的关系----》per
    3.轴长度直方图----》fg
    4.run time直方图----》per
    '''
    global savepath
    df_fg = pd.read_pickle(os.path.join(savepath, f'{line}fg.pkl'))
    df_fg.set_index('date', inplace=True)
    df_fg = df_fg.loc
    df_fg['PRODUCTION_DATE'] = df_fg['PRODUCTION_DATE'].astype(str).str[:10]

    df_per = pd.read_pickle(os.path.join(savepath, f'{line}per.pkl'))
    df_per.set_index('date', inplace=True)
    df_per = df_per.loc
    df_per['PRODUCTION_DATE'] = df_per['PRODUCTION_DATE'].astype(str).str[:10]

    # 筛选出近一个月的数据
    df_p = df_per.loc
    df_fg = df_fg.loc
    plt.figure(facecolor='white', figsize=(16, 9))
    sns.set(style="darkgrid")
    plt.rcParams['font.sans-serif'] = ['STZhongsong']# 中文字体设置-黑体
    plt.rcParams['axes.unicode_minus'] = False# 解决保存图像是负号'-'显示为方块的问题

    ax1 = plt.subplot(221)
    try:
      tu_1 = df_fg['段长'].value_counts()
      ax1 = tu_1.plot(kind='pie',
                        subplots=True,
                        # labels=labels,
                        # explode=(0,0.1,0,0),#突显
                        autopct=lambda x: my_label(x, tu_1),
                        # 设置百分比格式,保留一位#autopct=lambda x: my_label(x,data)
                        # autopct='%.1f%%',# 设置百分比格式,保留一位
                        pctdistance=0.8,# 设置百分比与圆心的距离
                        startangle=90,# 设置饼图的开始角度
                        radius=1,# 设置饼图的半径
                        counterclock=False,# 是否逆时针,false是顺时针
                        shadow=False,# 无阴影设置
                        labeldistance=1.1,# 默认1.1
                        # rotatelabels=True# True,标签放线是沿半径方向
                        textprops={'fontsize': 13}
                        )
      plt.axis('scaled')# 'tight''scaled'
      plt.ylabel('')
      plt.xlabel('')
      plt.title(f'{start}~{end}\n{line} Line 段长分布饼图\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print('段长分布饼图',e)
    ax2 = plt.subplot(222)
    try:
      tu_2 = df_p.groupby('OPERATOR')['RUN_TIME_HOUR'].agg('sum').sort_values(ascending=True)
      ax2=tu_2.plot(kind='pie',
                           subplots=True,
                           # labels=labels,
                           # explode=(0,0.1,0,0),#突显
                           autopct=lambda x: my_label(x, tu_2),# 设置百分比格式,保留一位#autopct=lambda x: my_label(x,data)
                           # autopct='%.1f%%',# 设置百分比格式,保留一位
                           pctdistance=0.8,# 设置百分比与圆心的距离
                           startangle=90,# 设置饼图的开始角度
                           radius=1,# 设置饼图的半径
                           counterclock=True,# 是否逆时针,false是顺时针
                           shadow=False,# 无阴影设置
                           labeldistance=1.1,# 默认1.1
                           # rotatelabels=True# True,标签放线是沿半径方向
                           textprops={'fontsize': 13}
                           )
      plt.axis('scaled')# 'tight''scaled'
      plt.ylabel('')
      plt.xlabel('')
      plt.title('\n Run_Time VS 人员分布饼图\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print('runtime饼图',e)
    ax3 = plt.subplot(223)
    try:
      tu_3 = df_fg
      ax3 = sns.distplot(
            tu_3['COIL_LENGTH'],
            bins='auto', ##auto,fd,doane,scott,stone,rice,sturges,sqrt
            hist=True,
            rug=False)
      ax3.tick_params(axis='x', labelsize=13)
      ax3.tick_params(axis='y', labelsize=13)
      plt.xlabel('轴长度 / m',fontsize=15)
      plt.title( '\n轴长度直方图\n',fontsize=18, fontweight='bold')
    except Exception as e:
      print('段长分布直方图',e)
    ax4 = plt.subplot(224)
    try:
      tu_8 = df_p
      ax4=sns.distplot(
                tu_8['RUN_TIME_HOUR'],
                bins='auto',
                hist=True,
                rug=False)
      ax4.tick_params(axis='x', labelsize=13)
      ax4.tick_params(axis='x', labelsize=13)
      plt.xlabel('run_time / h',fontsize=15)
      plt.title('\n Run_Time 直方图\n',fontsize=18, fontweight='bold')
    except Exception as e:
      print('runtime直方图',e)
    plt.tight_layout()
    plt.show()
    return
#画图函数4,ui上点击按钮对应画图
def out4_data(start=now_30ago,end=now):
    '''
    1.每条产线段长箱图
    2.每条产线的runtime箱图
    3.每条产线的oee箱图
    4. 每条产线的top3停车时长之和占总的监控运行时间占比饼图
    5.每个人OEE箱图

    '''
    df_p = pd.read_pickle(os.path.join(savepath, 'per2021_all.pkl'))
    df_p.set_index('date',inplace=True)
    #计算运行时间
    df_p = df_p.loc
    yunxingshijian = df_p.groupby('line')['TOTAL_TIME_HOUR'].agg('sum')
    # print(yunxingshijian)

    df_fg = pd.read_pickle(os.path.join(savepath, 'fg2021_all.pkl'))
    df_fg.set_index('date', inplace=True)
    df_fg = df_fg.loc

    df_s = pd.read_pickle(os.path.join(savepath, 'stop2021_all.pkl'))
    df_s.set_index('date',inplace=True)
    df_s = df_s.loc[['line','STOP_REASON','STOP_TIME_HOUR']]
    # print(df_s.info())
    df_s['计数'] = df_s.groupby(['line','STOP_REASON']).transform('count')
    #按照产线和原因分组,按照次数的top3进行时长求和
    df_s1 = df_s.groupby(['line', 'STOP_REASON', '计数']).sum().groupby('line', as_index=False).apply(
      lambda x: x.sort_values('计数', ascending=False).head(3))
    #每条线前三的时长之和
    df_s2 = df_s1.groupby('line')['STOP_TIME_HOUR'].agg('sum')

    df_s3 = pd.concat(,axis=1)
    df_s3.reset_index(inplace=True)
    df_s3['tingchezhanbi']=df_s3['STOP_TIME_HOUR']/df_s3['TOTAL_TIME_HOUR']
    # print(df_s3)
    # df_s3.to_excel('2.xlsx')
    # y = df_s2.values/yunxingshijian.values
    # x = yunxingshijian.index.tolist()
    # print(x)
    # print(y)

    plt.figure(facecolor='white', figsize=(16, 9))
    sns.set(style="darkgrid")
    plt.rcParams['font.sans-serif'] = ['STZhongsong']# 中文字体设置-黑体
    plt.rcParams['axes.unicode_minus'] = False# 解决保存图像是负号'-'显示为方块的问题
    ax1 = plt.subplot(241)
    try:
      ax1 = sns.boxplot(
                x='line',
                y='COIL_LENGTH',
                data=df_fg,
                order=['A','B', 'C', 'CB','CCV'])
      tu_1 = df_fg.groupby('line')['COIL_LENGTH'].median()
      # print(tu_13)
      tu_1_ = df_fg.groupby('line')['COIL_LENGTH'].describe()['25%']
      tu_1__ = df_fg.groupby('line')['COIL_LENGTH'].describe()['75%']
      for i, v in enumerate(tu_1.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                         ha='center',
                         va='bottom',
                         fontsize=12)
      for i, v in enumerate(tu_1_.values):
                a = round(float(v.__str__().strip('[,]')), 1)
                plt.text(i, v, a,
                         ha='center',
                         va='bottom',
                         fontsize=12)
      for i, v in enumerate(tu_1__.values):
                a = round(float(v.__str__().strip('[,]')), 1)
                plt.text(i, v, a,
                         ha='center',
                         va='bottom',
                         fontsize=12)
      ax1.tick_params(axis='x', labelsize=18)
      ax1.tick_params(axis='y', labelsize=16)
      plt.xlabel('')
      plt.ylabel('coil_lenth/m', fontsize=18, fontweight='bold')
      ax1.set_title(f'\n{start}-{end}\nCoil_Length vs Line\n', fontsize=24, fontweight='bold')
    except Exception as e:
      print('轴段长箱图',e)
    ax2 = plt.subplot(242)
    try:
      ax2 = sns.boxplot(
            x='line',
            y='RUN_TIME_HOUR',
            data=df_p,
            order=['A', 'B', 'C', 'CB', 'CCV'])
      tu_2 = df_p.groupby('line')['RUN_TIME_HOUR'].median()
      # print(tu_14)
      tu_2_ = df_p.groupby('line')['RUN_TIME_HOUR'].describe()['25%']
      tu_2__ = df_p.groupby('line')['RUN_TIME_HOUR'].describe()['75%']
      for i, v in enumerate(tu_2.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(tu_2_.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)

      for i, v in enumerate(tu_2__.values):
            a = round(float(v.__str__().strip('[,]')), 1)
            plt.text(i, v, a,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      ax2.tick_params(axis='x', labelsize=18)
      ax2.tick_params(axis='y', labelsize=16)
      plt.xlabel('')
      plt.ylabel('run_time/h', fontsize=18, fontweight='bold')
      ax2.set_title('\nRun_Time vs Line\n', fontsize=24, fontweight='bold')
    except Exception as e:
      print('runtime箱图',e)
    ax3 = plt.subplot(243)
    try:
      ax3 = sns.boxplot(
            x='line',
            y='OEE',
            data=df_p,
            order=['A', 'B', 'C', 'CB', 'CCV'])
      tu_3 = df_p.groupby('line')['OEE'].median()
      tu_3_ = df_p.groupby('line')['OEE'].describe()['25%']
      tu_3__ = df_p.groupby('line')['OEE'].describe()['75%']
      for i, v in enumerate(tu_3.values):
            a = float(v.__str__().strip('[,]'))
            b = '%.01f%%' % (a * 100)
            # print(a,type(a))
            plt.text(i, v, b,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(tu_3_.values):
            a = float(v.__str__().strip('[,]'))
            b = '%.01f%%' % (a * 100)
            # print(a,type(a))
            plt.text(i, v, b,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(tu_3__.values):
            a = float(v.__str__().strip('[,]'))
            b = '%.01f%%' % (a * 100)
            # print(a,type(a))
            plt.text(i, v, b,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      ax3.tick_params(axis='x', labelsize=18)
      ax3.tick_params(axis='y', labelsize=16)
      # ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
      plt.ylim(0, 1.2)
      plt.xlabel('')
      plt.ylabel('OEE/%', fontsize=18, fontweight='bold')
      ax3.set_title('\nOEE vs Line\n', fontsize=24, fontweight='bold')
    except Exception as e:
      print('OEE箱图',e)

    ax4 = plt.subplot(244)
    try:
      axx=sns.barplot(x='line',
                  y='tingchezhanbi',
                  data=df_s3,
                  ci=0,
                  # color='blue',
                  ax=ax4)

      for p in axx.patches:
            height = p.get_height()
            axx.text(x=p.get_x(),
                     y=height+0.02,
                     s='%.01f%%' % (height * 100),
                     color='black',
                     size=12)
      # plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      ax4.tick_params(axis='x', labelsize=18)
      ax4.tick_params(axis='y', labelsize=16)
      plt.xlabel('')
      plt.ylabel('top3 停车/运行时间', fontsize=16, fontweight='bold')
      ax4.set_title('\nTop3停车占系统运行时间\n', fontsize=24, fontweight='bold')

    # try:
    #   plt.bar(x,y,color=["brown", "green", "red", "grey", "purple"],alpha=0.8)
    #   for a,b in zip(x,y):
    #         ax4.text(a,b+0.02,'%.01f%%' % (b * 100),
    #                  ha='center',
    #                  va='bottom',
    #                  fontsize=12)
    #   ax4.tick_params(axis='x', labelsize=18)
    #   ax4.tick_params(axis='y', labelsize=16)
    #   plt.ylim(0,1.0)
    #   plt.xlabel('')
    #   plt.ylabel('top3 stop/sys total time%', fontsize=18, fontweight='bold')
    #   plt.title('\ntop3stop/sys total time\n', fontsize=24, fontweight='bold')
    except Exception as e:
      print('三大停车时间/运行时间占比',e)

    ax5 = plt.subplot(212)
    try:
      tu_5_ = df_p.groupby('OPERATOR')['OEE'].describe()
      order_list = tu_5_.index.tolist()
      ax = sns.boxplot(x='OPERATOR',
                         y='OEE',
                         data=df_p,
                         order=order_list
                         )
      tu_5 = df_p.groupby('OPERATOR')['OEE'].median()
      tu_5_ = df_p.groupby('OPERATOR')['OEE'].describe()['25%']
      tu_5__ = df_p.groupby('OPERATOR')['OEE'].describe()['75%']
      for i, v in enumerate(tu_5.values):
            a = float(v.__str__().strip('[,]'))
            b = '%.01f%%' % (a * 100)
            # print(a,type(a))
            plt.text(i, v, b,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(tu_5_.values):
            a = float(v.__str__().strip('[,]'))
            b = '%.01f%%' % (a * 100)
            # print(a,type(a))
            plt.text(i, v, b,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      for i, v in enumerate(tu_5__.values):
            a = float(v.__str__().strip('[,]'))
            b = '%.01f%%' % (a * 100)
            # print(a,type(a))
            plt.text(i, v, b,
                     ha='center',
                     va='bottom',
                     fontsize=12)
      ax5.tick_params(axis='x', labelsize=18)
      ax5.tick_params(axis='y', labelsize=16)
      ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
      plt.ylim(0, 1.2)
      plt.xlabel('')
      plt.ylabel('OEE/%', fontsize=16, fontweight='bold')
      plt.title('\nOEE vs Stuff\n', fontsize=24, fontweight='bold')
    except Exception as e:
      print('OEE个人箱图',e)
    plt.tight_layout()
    plt.show()
    return df_s1
#画图函数5,ui上点击按钮对应画图
def out11_data(line,start,end):
    '''
    1.白班和夜班的速度效率(速度效率---per)
    2.白班和夜班FTQ(质量生产判定---fg)
    3.白班和夜班RUN_TIME(runtime---per)
    4.白班和夜班OEE(oee---per)
    5.15天产量(real_length---fg)
    6.runtime饼图(runtime---per)
    '''
    global savepath
    df_fg = pd.read_pickle(os.path.join(savepath, f'{line}fg.pkl'))
    df_fg.set_index('date', inplace=True)
    df_fg = df_fg.loc
    df_fg['PRODUCTION_DATE'] = df_fg['PRODUCTION_DATE'].astype(str).str[:10]
    # print(df_fg)

    # df_per = pd.read_excel(os.path.join(savepath, f'{line}per.xlsx'))
    df_per = pd.read_pickle(os.path.join(savepath, f'{line}per.pkl'))
    df_per.set_index('date', inplace=True)
    df_per = df_per.loc
    df_per['PRODUCTION_DATE']=df_per['PRODUCTION_DATE'].astype(str).str[:10]
    # print(df_per)

    df_stop = pd.read_pickle((os.path.join(savepath, f'{line}stop.pkl')))
    df_stop['PRODUCTION_DATE'] = df_stop['PRODUCTION_DATE'].astype(str).str[:10]
    df_stop.set_index('date', inplace=True)


    #----------------------------------------------------
    plt.figure(facecolor='white', figsize=(16, 9))
    sns.set(style="darkgrid")
    plt.rcParams['font.sans-serif'] = ['STZhongsong']# 中文字体设置-黑体
    plt.rcParams['axes.unicode_minus'] = False# 解决保存图像是负号'-'显示为方块的问题

    try:
      ax1 = plt.subplot(231)
      sns.lineplot(x='PRODUCTION_DATE',
                   y='SPEED_EFFICIENCY',
                   data=df_per,
                   hue='SHIFT',
                  marker='*',
                   ax=ax1)
      for x,y in zip(df_per['PRODUCTION_DATE'],df_per['SPEED_EFFICIENCY']):
            if y<0.95:
                plt.text(x=x,y=y+0.02,s='%.01f%%' % (y * 100),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      plt.ylim(0, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('速度效率 / %', fontsize=14, fontweight='bold')
      ax1.set_title(f'{line} Line 15天 速度效率 %\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 速度效率')

    ax2 = plt.subplot(232)
    try:
      zongshu = df_fg.groupby(['PRODUCTION_DATE', 'PRODUCTION_SHIFT'], as_index=False)['itp'].agg('count')
      df_fg_hege = df_fg == 'False']
      hegeshu = df_fg_hege.groupby(['PRODUCTION_DATE','PRODUCTION_SHIFT'],as_index=False)['itp'].agg('count')
      df_ftq = pd.concat(,axis=1)
      df_ftq.columns = ['PRODUCTION_DATE','PRODUCTION_SHIFT','zongshu','date','SHIFT','hegeshu']
      df_ftq['FTQ']=df_ftq['hegeshu']/df_ftq['zongshu']
      # print(df_ftq)
      sns.lineplot(x='PRODUCTION_DATE',
                     y='FTQ',
                     data=df_ftq,
                     hue='SHIFT',
                     marker='*',
                     ax=ax2)
      for x,y in zip(df_ftq['PRODUCTION_DATE'],df_ftq['FTQ']):
            if y<0.1:
                plt.text(x=x,y=y+0.02,s='%.01f%%' % (y * 100),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('FTQ / %', fontsize=14, fontweight='bold')
      ax2.set_title(f'{line} Line 15天 FTQ %\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 FTQ')
    ax3 = plt.subplot(233)
    try:
      sns.lineplot(x='PRODUCTION_DATE',
                     y='RUN_TIME_HOUR',
                     data=df_per,
                     hue='SHIFT',
                     marker='*',
                     ax=ax3)
      for x,y in zip(df_per['PRODUCTION_DATE'],df_per['RUN_TIME_HOUR']):
            plt.text(x=x,y=y,s=round(y,1),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('run_time / h', fontsize=14, fontweight='bold')
      ax3.set_title(f'{line} Line 15天 Run_Time h\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 Run_Time')

    ax4 = plt.subplot(234)
    try:
      sns.lineplot(x='PRODUCTION_DATE',
                     y='OEE',
                     data=df_per,
                     hue='SHIFT',
                     marker='*',
                     ax=ax4)
      for x,y in zip(df_per['PRODUCTION_DATE'],df_per['OEE']):
            plt.text(x=x,y=y,s='%.01f%%' % (y * 100),color='red',size=14)

      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('OEE / %', fontsize=14, fontweight='bold')
      ax4.set_title(f'{line} Line 15天 OEE %\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 OEE')

    ax5 = plt.subplot(235)
    try:
      ax = sns.barplot(x='PRODUCTION_DATE',
                         y='TOTAL_LENGTH',
                         data=df_per,
                         hue='SHIFT',
                         ci=0,
                         ax=ax5)
      for p in ax.patches:
            height = p.get_height()
            ax.text(x=p.get_x() ,
                  y=height + 2,
                  s='{: .0f}m'.format(height), color='red', size=14)
      plt.xticks(ha='right', rotation=45)
      # plt.ylim(0.6, 1.2)
      plt.xticks(fontsize=13)
      plt.yticks(fontsize=13)
      plt.xlabel('')
      plt.ylabel('length / m', fontsize=14, fontweight='bold')
      ax5.set_title(f'{line} Line 15天 产量/ m\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天 产量')
    #############################################
    ax6 = plt.subplot(236)
    try:
      bing = df_per.groupby('SHIFT')['RUN_TIME_HOUR'].agg('sum').sort_values(ascending=True)
      ax6 = bing.plot(kind='pie',
                        subplots=True,
                        # labels=labels,
                        # explode=(0,0.1,0,0),#突显
                        # autopct='%.1f%%',# 设置百分比格式,保留一位
                        autopct=lambda x: my_label(x, bing),
                        pctdistance=0.8,# 设置百分比与圆心的距离
                        startangle=90,# 设置饼图的开始角度
                        radius=1,# 设置饼图的半径
                        counterclock=True,# 是否逆时针,false是顺时针
                        shadow=False,# 无阴影设置
                        labeldistance=1.1,# 默认1.1
                        # rotatelabels=True# True,标签放线是沿半径方向
                        textprops={'fontsize': 13}
                        )
      plt.axis('scaled')# 'tight''scaled'
      plt.ylabel('')
      plt.xlabel('')
      plt.title('\n15天白夜班开车时间占比\n', fontsize=18, fontweight='bold')
    except Exception as e:
      print(e,'15天白夜班开车时间占比')
    plt.tight_layout()
    plt.show()
    return




下边是ui的py文件
ui上有各数据加载的按钮,点击加载按钮,调用database文件中的3个合并文件的函数
其他的按钮就是对应出图的


from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUiType
from threading import Thread
import database as db
import datetime

now = datetime.datetime.now().strftime('%Y-%m-%d')
now_15ago=(datetime.datetime.now()-datetime.timedelta(days=14)).strftime('%Y-%m-%d')
now_1ago=(datetime.datetime.now()-datetime.timedelta(days=1)).strftime('%Y-%m-%d')



#UI--Logic分离
ui,_ = loadUiType('main_2021new.ui')

class Signal_progressbar(QObject):
    progress_update = pyqtSignal(int)
#实例化信号
so = Signal_progressbar()
class Mainapp(QMainWindow,ui):

    #定义构造方法
    def __init__(self):
      QMainWindow.__init__(self)
      self.setupUi(self)
      self.handle_ui_change()
      self.handle_buttons()
      so.progress_update.connect(self.setProgress)
      self.hebing_progressBar.setRange(0, 4)
      self.ongoing = False
      self.jishu_dateEdit.setDate(QDate.currentDate())
      self.kaishi_dateEdit.setDate(QDate.fromString(now_15ago, "yyyy-MM-dd"))

    # UI变化处理
    def handle_ui_change(self):
      self.tabWidget.tabBar().setVisible(True)

    # 处理所按钮的消息与槽的通信
    def handle_buttons(self):
      self.queding_pushButton.clicked.connect(self.hebing_click)
      self.tuichu_pushButton.clicked.connect(QCoreApplication.quit)

      self.a1_pushButton.clicked.connect(lambda: self.out1_click('A'))
      self.b1_pushButton.clicked.connect(lambda: self.out1_click('B'))
      self.c1_pushButton.clicked.connect(lambda: self.out1_click('C'))
      self.cb1_pushButton.clicked.connect(lambda: self.out1_click('CB'))
      self.ccv1_pushButton.clicked.connect(lambda: self.out1_click('CCV'))

      self.a2_pushButton.clicked.connect(lambda: self.out2_click('A'))
      self.b2_pushButton.clicked.connect(lambda: self.out2_click('B'))
      self.c2_pushButton.clicked.connect(lambda: self.out2_click('C'))
      self.cb2_pushButton.clicked.connect(lambda: self.out2_click('CB'))
      self.ccv2_pushButton.clicked.connect(lambda: self.out2_click('CCV'))

      self.aa1_pushButton.clicked.connect(lambda: self.out11_click('A'))
      self.bb1_pushButton.clicked.connect(lambda: self.out11_click('B'))
      self.cc1_pushButton.clicked.connect(lambda: self.out11_click('C'))
      self.cbcb1_pushButton.clicked.connect(lambda: self.out11_click('CB'))
      self.ccvccv1_pushButton.clicked.connect(lambda: self.out11_click('CCV'))

      self.aa2_pushButton.clicked.connect(lambda: self.out2_click('A'))
      self.bb2_pushButton.clicked.connect(lambda: self.out2_click('B'))
      self.cc2_pushButton.clicked.connect(lambda: self.out2_click('C'))
      self.cbcb2_pushButton.clicked.connect(lambda: self.out2_click('CB'))
      self.ccvccv2_pushButton.clicked.connect(lambda: self.out2_click('CCV'))

      self.aa3_pushButton.clicked.connect(lambda: self.out3_click('A'))
      self.bb3_pushButton.clicked.connect(lambda: self.out3_click('B'))
      self.cc3_pushButton.clicked.connect(lambda: self.out3_click('C'))
      self.cbcb3_pushButton.clicked.connect(lambda: self.out3_click('CB'))
      self.ccvccv3_pushButton.clicked.connect(lambda: self.out3_click('CCV'))

      self.box_pushButton.clicked.connect(lambda: self.out4_click())


    def kaishi_jieshu_click(self):
      start = self.kaishi_dateEdit.text()
      end = self.jishu_dateEdit.text()
      print(start,end)
      return (start,end)

    def hebing_click(self):
      try:
            def workerThread():
                self.ongoing = True
                self.hebing_progressBar.setRange(0, 3)
                db.concat_file_per()
                so.progress_update.emit(1)
                db.concat_file_fg()
                so.progress_update.emit(2)
                db.concat_file_stop()
                so.progress_update.emit(3)
                self.ongoing = False
            if self.ongoing:
                QMessageBox.warning(self.window(), '警告', '任务进行中,请等待完成')
                return
            worker = Thread(target=workerThread)
            worker.start()
      except Exception as e:
            print(e)

    def setProgress(self, value):
      self.hebing_progressBar.setValue(value)

    def out1_click(self,line):#近15天
      db.out1_data(line,start=now_15ago,end=now,now_1=now_1ago)

    def out2_click(self,line):
      start, end = self.kaishi_jieshu_click()
      db.out2_data(line,start,end)

    def out11_click(self,line):
      start, end = self.kaishi_jieshu_click()
      db.out11_data(line,start,end)
    def out3_click(self,line):
      start, end = self.kaishi_jieshu_click()
      db.out3_data(line,start,end)

    def out4_click(self):
      start, end = self.kaishi_jieshu_click()
      db.out4_data(start,end)


def main():
    app = QApplication([])
    window = Mainapp()
    window.show()
    app.exec_()


if __name__ == '__main__':
    main()

@hrp

rsj0315 发表于 2021-1-21 15:55:20

打包命令是 pyinstaller -w -D xxx.py
形成的文件夹下多个文件的形式。
问题是:
首次双击exe打开时,启动时间比较久。我打开了任务管理器后。
给其他人电脑(没有python)启动时,时间快10s了,令人发指。。

rsj0315 发表于 2021-1-21 15:58:57

各位帮忙看看哪款还有优化空间。
或者怎么写才更python

_2_ 发表于 2021-1-21 21:27:49

rsj0315 发表于 2021-1-21 15:58
各位帮忙看看哪款还有优化空间。
或者怎么写才更python

你的代码好长啊,不大想看了 = =
可以找找论坛里别的打包 exe 的方法,以前似乎发过一个方案但我忘记了

hrp 发表于 2021-1-21 21:54:29

本帖最后由 hrp 于 2021-1-21 23:33 编辑

rsj0315 发表于 2021-1-21 15:58
各位帮忙看看哪款还有优化空间。
或者怎么写才更python

目前粗略测试发现matplotlib和seaborn和pandas这三个包导入比较慢,加起来占2~3秒时间,matplotlib和seaborn占大头。
其中seaborn是对matplotlib的封装,如果可能的话把它们其中之一干掉,全部用另一个来实现功能,可以节省不少启动时间。
还有就是python环境安装太多的包,打包的时候会带入其他不需要的库,所以尝试用Anaconda3创建一个干净的虚拟python环境,只安装需要的包再打包,可能启动耗时会有好转。






技术水平有限,实在不好意思{:10_284:}{:10_284:}

yywwf2003 发表于 2021-1-21 23:59:58

这么厉害

rsj0315 发表于 2021-1-22 08:25:20

hrp 发表于 2021-1-21 21:54
目前粗略测试发现matplotlib和seaborn和pandas这三个包导入比较慢,加起来占2~3秒时间,matplotlib和se ...

收到感谢,画图的两个包去掉一个的话,估计也是seaborn,但是全matplotlib也画风也忒单调了。
我准备尝试安装个新的环境。打包下试试。

有一点我要说明下,我每次打包都是把这两个py文件和ui拿到桌面,放到一个文件夹里,然后开始打包的。
我要是装一个新的虚拟环境应该如何操作呢?还是拖到桌面?

hrp 发表于 2021-1-22 09:15:02

rsj0315 发表于 2021-1-22 08:25
收到感谢,画图的两个包去掉一个的话,估计也是seaborn,但是全matplotlib也画风也忒单调了。
我准备尝 ...

文件放在哪里跟用什么py环境没有关系的。
如果你会用anaconda3的话打开anaconda3的命令行窗口,输入conda create -n 环境名字比如py38 python=3.8创建一个虚拟环境,激活它,然后安装pyinstaller和运行你程序所需的第三方包,然后用pyinstaller打包,具体用法版主有发帖

weiter 发表于 2021-1-25 21:15:18

建议把install改成from……install……?
不知道只导入需要的功能会不会好一些,毕竟导这么多包不卡是肯定不可能的
但是我的想法在您这个的规模下有点高工作量……

Ⅲ只小猪 发表于 2021-1-26 09:08:35

rsj0315 发表于 2021-1-21 15:58
各位帮忙看看哪款还有优化空间。
或者怎么写才更python

可以参考一下这个方法:
https://fishc.com.cn/thread-90726-1-1.html

19924269098 发表于 2021-1-26 09:24:41

厉害

yywwf2003 发表于 2021-1-26 12:33:05

hrp 发表于 2021-1-21 21:54
目前粗略测试发现matplotlib和seaborn和pandas这三个包导入比较慢,加起来占2~3秒时间,matplotlib和se ...

大佬厉害
页: [1]
查看完整版本: 打包exe后,启动速度慢的问题