ragesz ragesz - 2 months ago 19
Python Question

python matplotlib plot table with multiple headers

I can plot my single-header dataframe on a figure with this code:

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


My question is: is it possible to plot a dataframe with multiindex columns? I want two separate "rows" for my multi-headers, so tuples in one header row is not good. If it is possible I want apply the above styles (colors) on both headers (it would be brilliant to set different colors for the multi headers).

Here is an example dataframe:

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


Result:

main
sub_1 sub_2
0 11 22
1 13 23

Answer

OK, I used a "trick" to solve this problem: plot a new table with only one cell, without column header and without row index. The only cell value is the original top header. And place this new table on the top of the old (single-header) table. (It is not the best solution but works...).

The code:

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