python matplotlib 图 table 有多个 headers

python matplotlib plot table with multiple headers

我可以使用以下代码在图形上绘制我的 single-header 数据框:

plt.table(cellText=df.round(4).values, cellLoc='center', bbox=[0.225, 1, 0.7, 0.15],
    rowLabels=['  {}  '.format(i) for i in df.index], rowLoc='center',
    rowColours=['silver']*len(df.index), colLabels=df.columns, colLoc='center',
    colColours=['lightgrey']*len(df.columns), colWidths=[0.1]*len(df.columns))

我的问题是:是否可以绘制具有多索引列的数据框?我的 multi-headers 需要两个单独的 "rows",所以一个 header 行中的元组不好。如果可能的话,我想在两个 headers 上应用上述样式(颜色)(为 multi headers 设置不同的颜色会很棒)。

这是一个示例数据框:

df = pd.DataFrame([[11, 22], [13, 23]],
    columns=pd.MultiIndex.from_tuples([('main', 'sub_1'), ('main', 'sub_2')]))

结果:

             main
    sub_1   sub_2
0      11      22
1      13      23

好的,我用 "trick" 解决了这个问题:绘制一个只有一个单元格、没有列 header 和行索引的新 table。唯一的单元格值是原始顶部 header。并将这个新的 table 放在旧的 (single-header) table 的顶部。 (这不是最好的解决方案,但有效...)。

代码:

df = pd.DataFrame([[11, 22], [13, 23]], columns=['sub_1', 'sub_2'])

# First plot single-header dataframe (headers = ['sub_1', 'sub_2'])
plt.table(cellText=df.round(4).values, cellLoc='center', bbox=[0.225, 1, 0.7, 0.15],
    rowLabels=['  {}  '.format(i) for i in df.index], rowLoc='center',
    rowColours=['silver']*len(df.index), colLabels=df.columns, colLoc='center',
    colColours=['lightgrey']*len(df.columns), colWidths=[0.1]*len(df.columns))

# Then plot a new table with one cell (value = 'main')
plt.table(cellText=[['main']], cellLoc='center', bbox=[0.225, 1.15, 0.7, 0.05],
    cellColours=[['Lavender']])