在matplotlib for循环中间遇到超时错误

问题描述 投票:0回答:1

我有一个代码,它将通过三个词典,如果所有键都匹配,则会作一些绘图。由于使用了matplotlib表,我遇到了一个奇怪的问题。

当我第一次运行此代码时,完成整个循环没有问题。现在第二次迭代遇到超时错误

我尝试将表移出for循环。我添加了plt.close('all')我还尝试在循环结束时再次导入matplotlib,以期在后端重置某些内容。

for k, v in oct_dict.items():
    for k2, v2 in stu_dict.items():
        for k3, v3 in oct2_dict.items():
            if k == k2 and k == k3:
                with PdfPages('{}.pdf'.format(k)) as pdf:
                        #rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
                        #v = v[v['a_1920'] != 0]
                    rc('text', usetex=True)
                    fig = plt.figure(figsize = (8,10.5))
                    gs=GridSpec(2,2) # 2 rows, 3 columns
                    ax0 = fig.add_subplot(gs[0,0])
                    ax0.bar(x=np.arange(2), height = [float(v['a_1920'])*100, mean_a_1920*100], color = nice)
                    plt.xticks(np.arange(2), ['{}'.format(k), 'D75'])

                    for p in ax0.patches:
                        a =p.get_height()
                        ax0.annotate('{:0.2f}'.format(float(a)), (p.get_x()+.1, p.get_height() * .75), weight = 'bold')
                    ax1 = fig.add_subplot(gs[0,1])


                    c = str(len(v2['student_id']))
                    c2 = int(v['c_1920'])
                    props = dict(boxstyle='round', facecolor='white', alpha=0.0)
                    c3 = int(v['b_1920'])
    # place a text box in upper left in axes coords
                    c4 = int(v['d_1920'])
                    ax1.text(0.0, 0.95, 'Number of  Age : {}'.format(c3), transform=ax1.transAxes, fontsize=12,
                                    verticalalignment='top')

                    ax1.text(0.0, 0.85, 'Number of Incomplete : {}'.format(c2), transform=ax1.transAxes, fontsize=12,
                                verticalalignment='top')
                    ax1.text(0.0, 0.75, 'Number of Invalid : {}'.format(c4), transform = ax1.transAxes, fontsize = 12,
                              verticalalignment = 'top' )
                    ax1.text(0.0, 0.65, 'Number of who will reach Age:\n{}'.format(c), transform=ax1.transAxes, fontsize=12,
                                 verticalalignment='top' )

                        #ax1.table(cellLoc = 'center', cellText = [] , loc = 'upper center')

                    ax1.axis('off')
                    ax1.axis('tight')
                        #fig.suptitle('Monthly Summary', va = 'top', ha= 'center')
                    fig.text(0.3, 1, 'Monthly Summary '+ dt.date.today().strftime("%b %d, %Y"),  fontsize=12, verticalalignment='top', bbox=props)
                        #plt.subplots_adjust(top = .75)
                        #plt.tight_layout()
                        #gs.constrained_layout()
                        #print(float(v3['inc']))
                        #print(float(v3['com']))
                    ax2 = fig.add_subplot(gs[1,0])

                    plt.sca(ax2)
                    p1 = plt.bar(np.arange(1), int(v3['com']), width=.25,color = 'b',label = 'Complete')
                    p2 = plt.bar(np.arange(1), int(v3['inc']), width = .25, bottom = int(v3['com']), color = 'r', label = 'Incomplete')
                    plt.legend()
                    for p in ax2.patches:

                        ax2.annotate((p.get_height()), (p.get_x()+.1, p.get_height() * .75), weight = 'bold')
                    ax2.set_xticks([])
                      # # #ax2.set_xlabel='Students Who Will Turn 15'
                    ax2.set_title('Students who will turn 15 later in the school year')
                    ax2.set_xticks([])
                    ax3 = fig.add_subplot(gs[1,1])
                    a = int(v3['com'])+int(v3['inc'])


                    ax3.axis('off')

                    plt.tight_layout()
                    pdf.savefig()
                    plt.close('all')  
                    fig = plt.figure(figsize = (8,11.5))
                    gs=GridSpec(1,1) 
                    axs = fig.add_subplot(gs[0])
                    cell_text = []
                    v2 = v2.drop(['Grand Total','birth_dte','loc'],axis = 1)
                    binarymap = {0:'No',1:'Yes'}
                    v2['Plan Not Complete'] = v2['Plan Not Complete'].map(binarymap)
                    v2['Plan Already Complete'] = v2['Plan Already Complete'].map(binarymap)
                    labels = [six column titles here]
                    for row in range(len(v2)):

                        try:

                            cell_text.append(v2.iloc[row])
                        except:
                            pass

                    table = axs.table(cellLoc = 'center', cellText = cell_text, colLabels = labels,
                                      rowLoc = 'center', colLoc = 'center',loc = 'upper center',fontsize = 32)
                    table.set_fontsize(32)
                    table.scale(1, 1.5)
                            #axs.text(0.0,0.5,'For the column')
                    axs.axis('off')
                    pdf.savefig()
                    #plt.savefig('{}_list.pdf'.format(k))
                    plt.show()
                    plt.close('all')
                    import matplotlib.pyplot as plt

TimeoutError:锁定错误:Matplotlib无法获取以下锁定文件:C:\ Users \ myusername.matplotlib \ tex.cache \ 23c95fa5c37310802233a994d78d178d.tex.matplotlib-lock

注意:如果某些键名在此代码中不匹配,则是故意的,由于此帖子是公开的,因此我不得不对其进行更改。一旦代码到达axs.table行,第二次迭代就会引发错误。

python loops matplotlib timeout
1个回答
0
投票

有效的方法,但我想避免的就是删除此脚本的tex。 rc param tex设置为False,代码也很快完成了运行]

© www.soinside.com 2019 - 2024. All rights reserved.