Python 3.x 使用seaborn对数据分组后的条形图

Python 3.x 使用seaborn对数据分组后的条形图,python-3.x,pandas,matplotlib,seaborn,pandas-groupby,Python 3.x,Pandas,Matplotlib,Seaborn,Pandas Groupby,我正在尝试使用seaborn.barplot在分组后绘制数据。我的第一种方法是使用以下方法生成新的数据帧: g_data = g_frame.groupby(["STG","GRP"])["HRE"].mean() g_data 以下是输出: STG GRP S1 Control 0.561871 OSA 0.589858 S2 Control 0.595950 OSA 0.629775 S3 Con

我正在尝试使用
seaborn.barplot
在分组后绘制数据。我的第一种方法是使用以下方法生成新的数据帧:

g_data = g_frame.groupby(["STG","GRP"])["HRE"].mean()
g_data
以下是输出:

STG   GRP    
S1    Control    0.561871
      OSA        0.589858
S2    Control    0.595950
      OSA        0.629775
S3    Control    0.629906
      OSA        0.674118
S4    Control    0.578875
      OSA        0.568370
S5    Control    0.557712
      OSA        0.569524
Name: HRE, dtype: float64
接下来,我定义了一个名为
plot\u v1(data)
的绘图函数,如下所示:

def plot_v2(data):

    # Create the bar plot
    ax = sns.barplot(
        x="STG", y="HRE", hue="GRP",
        order=["S1", "S2", "S3", "S4", "S5"],
        hue_order=["Control", "OSA"],
        data=data)

    # Return the figure object and axis
    return plt.gcf(), ax

plot_v2(g_data);
这引发了一个错误,即:

149                 if isinstance(input, string_types):
150                     err = "Could not interpret input '{}'".format(input)
--> 151                     raise ValueError(err)
152 
153             # Figure out the plotting orientation

ValueError: Could not interpret input 'STG'
我不确定我做错了什么。当我检查索引值时,它看起来很好

g_data.index
MultiIndex(levels=[['S1', 'S2', 'S3', 'S4', 'S5'], ['Control', 'OSA']],
       labels=[[0, 0, 1, 1, 2, 2, 3, 3, 4, 4], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]],
       names=['STG', 'GRP'])

不确定您的最终期望是什么,但以下是我的barplot方法:

df.groupby(["STG","GRP"]).mean().unstack().plot.bar()

试试
g\u data.reset\u index()
g\u frame.groupby(as\u index=False…)
太棒了!谢谢,这个有用。你知道我为什么要做这一步吗?这也行!就连布拉德·所罗门(Brad Solomon)也提到了替代方案。谢谢:)