Search code examples
pythonpandasmatplotlibannotationsscatter-plot

How to annotate points in a scatterplot based on a pandas column


Wanted 'Age' as the x-axis, 'Pos' as the y-axis and labels as 'Player' Names. But for some reason, not able to do label the points.

Code:

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



data = pd.read_excel("path to  the file")
fig, ax = plt.subplots()
fig.set_size_inches(7,3)

df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])

df.plot.scatter(x='Age',
                y='Pos',
                c='DarkBlue', xticks=([15,20,25,30,35,40]))

y = df.Player
texts = []
for i, txt in enumerate(y):
    plt.text()
at.adjust_text(texts, arrowprops=dict(arrowstyle="simple, head_width=0.25, tail_width=0.05", color='black', lw=0.5, alpha=0.5))

plt.show()

Summary of the data :

df.head()

             Player Pos  Age
0  Thibaut Courtois  GK   28
1     Karim Benzema  FW   32
2      Sergio Ramos  DF   34
3    Raphael Varane  DF   27
4       Luka Modric  MF   35

Error :

ConversionError: Failed to convert value(s) to axis units: 'GK'

This is the plot so far; not able to label these points: This is the plot so far; not able to label these points

EDIT: This is what I wanted but of all points: This is what I wanted, but of all points

Also, Could anyone help me in re-ordering the labels on the yaxis. Like, I wanted FW,MF,DF,GK as my order but the plot is in MF,DF,FW,GK.

Thanks.


Solution

  • A similar solution was described here. Essentially, you want to annotate the points in your scatter plot.

    I have stripped your code. Note that you need to plot the data with matplotlib (and not with pandas): df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age']). In this way, you can use the annotation()-method.

    import matplotlib.pyplot as plt
    import pandas as pd
    
    # build data
    data = [
    ['Thibaut Courtois', 'GK', 28],
    ['Karim Benzema', 'FW', 32],
    ['Sergio Ramos','DF', 34],
    ['Raphael Varane', 'DF', 27],
    ['Luka Modric', 'MF', 35],
    ]
    # create pandas DataFrame
    df = pd.DataFrame(data, columns = ['Player', 'Pos', 'Age'])
    
    
    # open figure + axis
    fig, ax = plt.subplots()
    # plot
    ax.scatter(x=df['Age'],y=df['Pos'],c='DarkBlue')
    # set labels
    ax.set_xlabel('Age')
    ax.set_ylabel('Pos')
    
    # annotate points in axis
    for idx, row in df.iterrows():
        ax.annotate(row['Player'], (row['Age'], row['Pos']) )
    # force matplotlib to draw the graph
    plt.show()
    

    This is what you'll get as output:

    picture