具有多个标题的python matplotlib绘图表

标签 python matplotlib multi-index

我可以使用以下代码在图形上绘制我的单标题数据框:

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

最佳答案

好吧,我用了一个“技巧”来解决这个问题:绘制一个只有一个单元格、没有列标题和行索引的新表格。唯一的单元格值是原始顶部标题。并将这个新表放在旧(单标题)表的顶部。 (这不是最好的解决方案,但有效...)。

代码:

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

关于具有多个标题的python matplotlib绘图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39289483/

相关文章:

python - 当默认目录为python2.7时,如何将beautifulsoup安装到python3中?

python - 我需要过滤或删除文件中的一些行

python - 具有线性 y 轴和对数 x 轴的最佳拟合线半对数刻度

python - 属性错误 : 'NoneType' object has no attribute 'magic'

python - 从 MultiIndex 中删除单个(子)列

python - 使用部分索引元组列表对多索引数据帧进行切片的最佳方法是什么?

Python Pandas MultiIndex Plot 图例的颜色不正确

python - 属性错误 : 'NoneType' object has no attribute '_meta'

python - 从python中的.ini文件读取特殊字 rune 本

python - 在 matplotlib 中更改颜色条渐变