Search code examples
python-3.xmatplotlibseabornscatter-plotmplcursors

Seaborn and mplcursors


I have some data that I want to plot on a scatter chart, and display the associated label for each point. The data looks like

xlist=[1,2,3,4]
ylist=[2,3,4,5]
labels=['a', 'b', 'c', 'd']

I can plot using Seaborn and tried to use mplcursor, but the displayed labels are the x and y instead of labels.

sns.scatterplot(x, y)
mplcursors.cursor(hover=True)

How can I make it display the labels, instead of (x, y)?


Solution

  • You will need to read the mplcursors documentation and copy the example on that matter from it to your code. Let me do that for you:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import mplcursors
    
    xlist=[1,2,3,4]
    ylist=[2,3,4,5]
    labels=['a', 'b', 'c', 'd']
    
    sns.scatterplot(xlist, ylist)
    
    cursor = mplcursors.cursor(hover=True)
    cursor.connect(
        "add", lambda sel: sel.annotation.set_text(labels[sel.target.index]))
    
    plt.show()