如何在Panda数据帧导出的表格图像下添加文本

时间:2017-09-13 12:17:30

标签: python matplotlib dataframe

如何使用Panda数据框在表格下添加一些文本? 我想把我的文字放在我的桌子下面,所以在这种情况下我可以做什么? image exported 我试图定位我的文字,但它不起作用。 我还尝试制作2个子图,一个用于表,一个用于其图例框,但后来我无法删除2个子图之间的空白区域。 继承我的代码:

    def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
                 header_color='dodgerblue', row_colors=['#f1f1f2', 'w'], edge_color='w',
                 bbox=[0, 0, 1, 1], header_columns=0,
                 ax=None, **kwargs):
    if ax is None:
        size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
        figi = plt.figure(figsize=size)
        ax=figi.add_subplot(2,1,1)
        ax.axis('off')


        note_legend=figi.add_subplot(2,1,2)
        note_legend.axis([0,100,0,100]) 
        note_legend.axis('off')

        l0='A*: Acier rompu'          
        l1='B*: Béton écrasé' 
        l2='C*: Cadre rompu'    
        l3='T*: Torseurs trop importants'
        l4='S*: Contraintes supplémentaires torsion/tranchant trop importantes'
        l5='R*: Combinaison torsion/tranchant non vérifiée'
        l6="V*: Résistance à l'effort tranchant de la section non suffisante"
        texte=(l0+'\n'+l1+'\n'+l2+'\n'+l3+'\n'+l4+'\n'+l5+'\n'+l6+'\n')
        note_legend.text(0,-2,texte,fontsize=11,family='monospace',style='italic')


    mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)
    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)

    for k, cell in  six.iteritems(mpl_table._cells):
        cell.set_edgecolor(edge_color)
        if k[0] == 0 or k[1] < header_columns:
                cell.set_text_props(style='italic',weight='medium',size='large',color='w')
                cell.set_facecolor(header_color)
        else:
                cell.set_facecolor(row_colors[k[0]%len(row_colors)])    
        if k[0]==0 and (k[1]==3 or k[1]==4 or k[1]==5 or k[1]==6):  
                cell.set_text_props(weight='bold',size='large',color='w')

    return ax

render_mpl_table(df, header_columns=0, col_width=2.0)

它给我这个:result

1 个答案:

答案 0 :(得分:0)

我认为一个需要对当前代码进行最少更改的解决方案就是创建不同高度的子图。

fig, (ax,note_legend)  = plt.subplots(nrows=2, figsize=size, 
                                      gridspec_kw=dict(height_ratios = [0.8,0.2]))
ax.axis('off')
note_legend.axis([0,100,0,100]) 
note_legend.axis('off')

上面将生成具有80%可用空间的表格轴,以及具有20%可用空间的图例轴。您仍然需要调整这些参数以适合您的实际数据。