熊猫:如何在MultiIndex中格式化图例

时间:2019-01-24 22:10:46

标签: python pandas multi-index

此刻,我正在处理带有MultiIndex Column的绘图。当我尝试在图表中绘制此类数据时(如下面的示例所示),在图例中收到“(Semester1,Maths)”,“(Semester1,Science)”等。

import pandas as pd
import numpy as np

header = pd.MultiIndex.from_product([['Semester1','Semester2'],['Maths','Science']])
d=([[12,45,67,56],[78,89,45,67],[45,67,89,90],[67,44,56,55]])


df = pd.DataFrame(d,
                  index=['Alisa','Bobby','Cathrine','Jack'],
                  columns=header)
df.plot(kind='bar')

我知道可以手动设置图例文本,但是还有一种方法可以将Columns用作一种变量,以便例如可以自动将图例调整为“ Semester1,Maths”格式而不是“(第1学期,数学)”?

感谢您的支持!

1 个答案:

答案 0 :(得分:0)

您可以在调用plot之前用所需的值替换列索引:

In [650]: df.set_axis(header.map(', '.join), axis=1, inplace=False)
Out[650]: 
          Semester1, Maths  Semester1, Science  Semester2, Maths  Semester2, Science
Alisa                   12                  45                67                  56
Bobby                   78                  89                45                  67
Cathrine                45                  67                89                  90
Jack                    67                  44                56                  55

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

header = pd.MultiIndex.from_product([['Semester1','Semester2'],['Maths','Science']])
d=([[12,45,67,56],[78,89,45,67],[45,67,89,90],[67,44,56,55]])

df = pd.DataFrame(d,
                  index=['Alisa','Bobby','Cathrine','Jack'],
                  columns=header)
df.set_axis(header.map(', '.join), axis=1, inplace=False).plot(kind='bar')
plt.show()

enter image description here