简体   繁体   中英

Annotate seaborn Factorplot

I would like to visualize 2 boolean informations stored as columns in one seaborn FactorPlot.

Here is my df :

在此输入图像描述

I would like to visualize both of actual_group and adviced_group in the same FactorPlot.

For now I am only able to plot the adviced_groups using the hue parameter :

在此输入图像描述

with the code below :

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

I tried to use the ax.annotate() from matplotlib without any success, because - for what I understood - Axes are not handled by the sns.FactorPlot() method.

It could be an annotation, colorize one of the rectangle's edge or anything that could help visualize the actual group.

The result could be for instance something like this :

在此输入图像描述

You could make use of plt.annotate method provided by matplotlib to make annotations for the factorplot as shown:

Setup:

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

Data Operations:

Choosing the subset of df where the values of actual_group are True. The index value and the nb_opportunities value become the arguments for x and y that become the location of the annotation.

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

Plotting:

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

Adding some padding to the location of the annotation as well as the location of text to account for the width of the bars being plotted.

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

图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM