2016-09-02 48 views
2

我可以画出我的单头数据帧上的数字与此代码:蟒蛇matplotlib阴谋表

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)) 

我的问题是:是否有可能情节与多指标列一个数据帧?我想要为我的多头文件分配两个“行”,所以一个头行中的元组不好。如果可能的话,我希望在两个标题上应用上述样式(颜色)(为多标题设置不同的颜色会很棒)。

下面是一个例子数据框:

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 

回答

1

OK,我用了一个“绝招”来解决这个问题:阴谋与只剩一个格的新表,无柱头和没有行索引。唯一的单元格值是原始顶部标题。将这个新表放在旧(单头)表的顶部。 (这不是最好的解决方案,但工程...)。

代码:

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']])