Annotating Swarmplot in Seaborn

1k Views Asked by At

So I'm still getting to grips with Python after coming over from R recently. I'm struggling to automatically annotate plots from DF Column. Which is easily done in R.

I was helped the other day on the same matter on MPL Scatter plots. But I've been tearing my hair out trying to figure this out. I'll add some random data, and show a picture of the sort of thing I'm after.

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt 
import matplotlib as mpl
import seaborn as sns
d = {'Player': ['Messi', 'Ronaldo','Mbappe','Kovacic', 'Werner','Salah'], '% of Squad pass': [3.2,3.2,4.4,9.9,7.4,4.8)
df = pd.DataFrame(data = d)

This is what I'm doing at the minute.

fig, ax = plt.subplots(1,1, figsize=(4,4))
sns.swarmplot(data=df, x ='% of Squad Pass', ax = ax)

Which gets me this,

Is there a loop function I can use that will automatically annotate the plot points with text from the 'Player' column in the dataframe?

So I'd end with something like this

enter image description here

Thanks and hopefully this will be my last question on the matter!

1

There are 1 best solutions below

2
On

This is my proposal. You need import random library.

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt 
import matplotlib as mpl
import seaborn as sns
import random

d = {'Player': ['Messi', 'Ronaldo','Mbappe','Kovacic', 'Werner','Salah'], '% of Squad pass': [3.2,3.2,4.4,9.9,7.4,4.8]}
df = pd.DataFrame(data = d)

fig, ax = plt.subplots()
sns.swarmplot(data = df, x=df['% of Squad pass'], ax = ax)

for i, j in enumerate(df['% of Squad pass']):
    plt.annotate(df['Player'][i],
                xy=(df['% of Squad pass'][i],0),
                xytext=(df['% of Squad pass'][i], random.uniform(0.2,0.4)),
                arrowprops=dict(arrowstyle="->"))