Search code examples
pythonmatplotlibseabornplot-annotationspairplot

How to annotate seaborn pairplots


I have a collection of binned data from which I generate a series of seaborn pairplots. Since all of the bins have the same labels, but not bin names, I need to annotate the pairplots with the bin name 'n' below so that I can later associate them with their bins.

import seaborn as sns
groups = data.groupby(pd.cut(data['Lat'], bins))
for n,g in groups:
    p = sns.pairplot(data=g, hue="Label", palette="Set2", 
                 diag_kind="kde", size=4, vars=labels)

I noted in the documentation that seaborn uses, or is built upon, matplotlib. I have been unable to figure out how to annotate the legend on the left, or provide a title above or below the paired plots. Can anyone provide examples of pointers to the documentation on how to add arbitrary text to those three areas of a plot?


Solution

  • After following up on mwaskom's suggestion to use matplotlib.text() (thanks), I was able to get the following to work as expected:

    p = sns.pairplot(data=g, hue="Label", palette="Set2", 
                 diag_kind="kde", size=4, vars=labels)
    #bottom labels
    p.fig.text(0.33, -0.01, "Bin: %s"%(n), ha ='left', fontsize = 15)
    p.fig.text(0.33, -0.04, "Num Points: %d"%(len(g)), ha ='left', fontsize = 15)
    

    and other useful functionality:

    # title on top center of subplot
    p.fig.suptitle('this is the figure title', verticalalignment='top', fontsize=20)
    
    # title above plot
    p.fig.text(0.33, 1.02,'Above the plot', fontsize=20)
    
    # left and right of plot
    p.fig.text(0, 1,'Left the plot', fontsize=20, rotation=90)
    p.fig.text(1.02, 1,'Right the plot', fontsize=20, rotation=270)
    
    # an example of a multi-line footnote
    p.fig.text(0.1, -0.08,
         'Some multiline\n'
         'footnote...',
          fontsize=10)