第一部分相对容易解决。当您创建
pandas
使用
dict
,关键字的顺序以及列的顺序不是固定的。要获得正确的排序,请使用
columns
关键字。第二部分有点棘手。我找到的解决方案
here
就是用第二个表覆盖原始表,然后在第二个表中添加另一个单元格,该单元格的高度与原始表的四个单元格相同。为此,您必须首先从表实例获取单元字典,并汇总表行的高度。请参见下面的代码:
import pandas as pd
import matplotlib.pyplot as plt
MinP_M=5
Min_M=6
Per_M=7
Per_G=8
Per2_M=9
PerFlat_M=10
MaxPL_M=11
Max_M=12
GF_M =13
fig1 = plt.figure()
##this line entirely messed up the plot for me (on Mac):
##fig1.set_size_inches(8.7,11.75,forward=True)
ax1=fig1.add_subplot(111)
ax1.axis('off')
ax1.axis('tight')
data2={'Min':['%s'%MinP_M,'%s'%Min_M,'',''],
'Typ':['%s'%Per_M,'%s'%Per_G,'%s'%Per2_M,'+/- %s'%PerFlat_M],
'Max':['%s'%MaxPL_M,'','%s'%Max_M,'+/- %s'%GF_M],
'Pass/Fail':['','','','']
}
##fix the column ordering with a list:
keys = ['Min', 'Typ', 'Max', 'Pass/Fail']
df2 = pd.DataFrame(data2, columns=keys)
##defining the size of the table cells
row_label_width = 0.05
col_width = 0.15
col_height = 0.05
the_table2=ax1.table(
cellText=df2.values,
colWidths=[col_width]*4,
rowLabels=['A','B','C', 'D'],
colLabels=df2.columns,
##loc='center', ##this has no effect if the bbox keyword is used
bbox = [0,0,col_width*4,col_height*5],
)
celld = the_table2.get_celld()
##getting the heights of the header and the columns:
row_height_tot = 0
for (i,j),cell in celld.items():
if j==3 and i>0: #last column, but not the header
row_height_tot += cell.get_height()
the_table3=ax1.table(
cellText=['0'], ##cannot be empty
colLabels=df2.columns[-1:],
colWidths=[col_width],
bbox = [col_width*3,0,col_width,col_height*5],
)
the_table3.add_cell(1,0,col_width,row_height_tot)
fig1.tight_layout()
plt.show()
我不得不关闭一些格式化选项,因为它们在我的电脑上给出了奇怪的结果。如果你想让桌子居中,可以玩
bbox
中的选项
table
命令。最终结果如下所示:
希望这有帮助。