注释seaborn Factorplot

时间:2016-08-25 14:05:20

标签: python pandas matplotlib seaborn

我想在一个seaborn FactorPlot中可视化存储为列的2个布尔信息。

这是我的df:

enter image description here

我想在同一个FactorPlot中同时显示actual_groupadviced_group

目前我只能使用adviced_groups参数绘制hue

enter image description here

使用以下代码:

 _ = sns.factorplot(x='groups',
                    y='nb_opportunities',
                    hue='adviced_groups',
                    size=6,
                    kind='bar',
                    data=df)

我尝试使用matplotlib中的ax.annotate()而没有任何成功,因为 - 据我所知 - 轴不是由sns.FactorPlot()方法处理的。

它可以是一个注释,着色矩形边缘之一或任何可以帮助可视化实际组的东西。

结果可能是这样的:

enter image description here

1 个答案:

答案 0 :(得分:6)

您可以使用matplotlib提供的plt.annotate方法为factorplot制作注释,如下所示:

设置:

df = pd.DataFrame({'groups':['A', 'B', 'C', 'D'],
                   'nb_opportunities':[674, 140, 114, 99],
                   'actual_group':[False, False, True, False],
                   'adviced_group':[False, True, True, True]})
print (df)

  actual_group adviced_group groups  nb_opportunities
0        False         False      A               674
1        False          True      B               140
2         True          True      C               114
3        False          True      D                99

数据操作:

选择df的值为actual_group的子集为True。 index值和nb_opportunities值成为x和y的参数,它们将成为注释的位置。

actual_group = df.loc[df['actual_group']==True]
x = actual_group.index.tolist()[0]
y = actual_group['nb_opportunities'].values[0]

绘图:

sns.factorplot(x="groups", y="nb_opportunities", hue="adviced_group", kind='bar', data=df, 
               size=4, aspect=2)

在注释的位置添加一些填充以及文本的位置以考虑正在绘制的条的宽度。

plt.annotate('actual group', xy=(x+0.2,y), xytext=(x+0.3, 300),
             arrowprops=dict(facecolor='black', shrink=0.05, headwidth=20, width=7))
plt.show()

Image

相关问题