0

我使用 matplotlib 创建了自定义表格,其中我在某些单元格中包装了长文本。它适用于plt.show(). 但是,当我使用plt.savefig()它保存图像时,它会丢失文本换行。以下是我正在使用的代码片段。有什么办法可以在保存图像后保持文字环绕效果。

table_vals=[['Long row header for Q0', '% Change values', '(0.x)%', 'x.y%', '(0.x)%', 'y.x%'], 
['92.0%', 'Q9 ', '91.0%', '89.1%', '90.1%', '100%']]

col_labels=['Description', 'Cycle Name', 'Column 1', 'Column 2', 'Column 3', 'very very long column name']
std_col_list_new=['Column 1', 'Column 2', 'Column 3', 'very very long column name']

fig = plt.figure()
ax = fig.add_subplot(111)
# Draw table
the_table = plt.table(cellText=table_vals,
                      colWidths=[0.1]*len(col_labels),
#                       rowLabels=row_labels,
                      colLabels=col_labels,
                      loc='center',
                     cellLoc='center')
the_table.auto_set_font_size(False)
the_table.set_fontsize(14)
the_table.scale(4, 4)

# plt.savefig('matplotlib-table.png', bbox_inches='tight', pad_inches=0.05)

mergecells(the_table, (2,0), (1,0),True)
the_table[(1,0)].set_text_props(wrap=True)
# the_table[(2,0)].set_text_props(va='top')
cells = the_table.properties()["celld"]
cells[1,0]._codes=17
cells[2,0]._codes=8
for i,col in zip(range(len(std_col_list_new)),std_col_list_new):
    if len(col)>10:
        cells[0,i+2].set_text_props(wrap=True)
    cells[1,i+2].set_text_props(color='w')
    cells[1,i+2].set_color('blue')
    cells[1,i+2].set_edgecolor('black')
    cells[2,i+2].set_text_props(color='w')
    cells[2,i+2].set_color('blue')
    cells[2,i+2].set_edgecolor('black')
the_table.properties()["celld"]=cells
#     plt.table()=the_table
# Removing ticks and spines enables you to get the figure only with table
plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
plt.tick_params(axis='y', which='both', right=False, left=False, labelleft=False)
for pos in ['right','top','bottom','left']:
    plt.gca().spines[pos].set_visible(False)
if save==True:
        fig.set_size_inches(6,4)
        plt.savefig('test.png', dpi=100,pad_inches=0.1,bbox_inches = 'tight',frameon=False)
plt.show()
4

0 回答 0