Annotate markers values on Seaborn line plot (sns)

13,870

Yes, it is possible with ax.text(...), by default the annotated text color is black. If you want to color group the labels, then a possible way is to do a groupby ax.text(...) loop (with your predefined color palette) as follows,

Import libraries and create a sample data frame

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

np.random.seed(12345)
x = np.random.rand(15,3)
y = np.random.binomial(2, 0.5, (15,1))
z = np.concatenate((x,y),axis=1)

df = pd.DataFrame(z,columns=['x','y','mark_value','label'])
df['label'] = df['label'].astype(int)
print(df)
#            x         y  mark_value  label
# 0   0.929616  0.316376    0.183919      1
# 1   0.204560  0.567725    0.595545      1
# 2   0.964515  0.653177    0.748907      1
# 3   0.653570  0.747715    0.961307      1
# 4   0.008388  0.106444    0.298704      0
# 5   0.656411  0.809813    0.872176      1
# 6   0.964648  0.723685    0.642475      0
# 7   0.717454  0.467599    0.325585      2
# 8   0.439645  0.729689    0.994015      2
# 9   0.676874  0.790823    0.170914      1
# 10  0.026849  0.800370    0.903723      0
# 11  0.024676  0.491747    0.526255      1
# 12  0.596366  0.051958    0.895090      1
# 13  0.728266  0.818350    0.500223      2
# 14  0.810189  0.095969    0.218950      2

Code for plotting

a4_dims = (20, 10)
fig, ax = plt.subplots(figsize=a4_dims)

palette = ['r','b','g']

p1 = sns.lineplot(x='x', y='y', hue='label', style='label', markers=True, dashes=False, 
             data=df, palette=palette)

for item, color in zip(df.groupby('label'),palette):
    #item[1] is a grouped data frame
    for x,y,m in item[1][['x','y','mark_value']].values:
        ax.text(x,y,f'{m:.2f}',color=color)

Output enter image description here

Share:
13,870

Related videos on Youtube

Fabio Magarelli
Author by

Fabio Magarelli

I'm a software developer with experience in Healthcare and Research. I like working remotely most of the time but also have the opportunity to meet my team in the office (wherever that may be). I am eager to learn and have no problem stepping out of my comfort zone in order to achieve my goals.

Updated on June 04, 2022

Comments

  • Fabio Magarelli
    Fabio Magarelli almost 2 years

    is there a way to annotate the markers value on a Seaborn line plot?

    This is my actual line plot:

    a4_dims = (20, 10)
    fig, ax = plt.subplots(figsize=a4_dims)
    p1 = sns.lineplot(x='NBags', y='value', hue='variable', style="variable", markers=True, dashes=False, 
                 data=pd.melt(df_knn1, ['NBags']))
    

    enter image description here

    And This is what I want: enter image description here

    Where the numeric values on each marker is the value of the marker itself on the line.