chen abien
chen abien

Reputation: 197

How do I achieve hover xy data for matplotlib

I am trying to plot a graph:

ax = df.plot(x=1, y=2, marker = 'D', markersize=4)

X axis is from column 1 and y axis from column 2.
Is it possible to obtain the (x,y) on mouse hover?

Upvotes: 2

Views: 1588

Answers (1)

JohanC
JohanC

Reputation: 80289

mplcursors is a library from some matplotlib developers to help in showing annotations while hovering. Here is an example:

import matplotlib.pyplot as plt
import mplcursors
import pandas as pd
import numpy as np

def show_info(sel):
    ind = sel.target.index
    sel.annotation.set_text(f'{df.loc[ind, "Name"]}:\nHeight:{df.loc[ind, "Height"]}\nWeight:{df.loc[ind, "Weight"]}')

heights = [174, 147, 155, 172, 187, 144, 181, 172, 143, 178, 181, 198, 142, 154, 159, 144, 194, 171, 140, 140, 192, 174,
           177, 158, 141, 184, 145, 183, 188, 181, 191, 153, 159, 141, 168, 190, 166, 149, 151, 188, 171, 142, 187, 179,
           184, 174, 151, 178, 177, 169, 169, 165, 140, 165, 182, 146, 176, 179, 198, 183, 187, 173]
weights = [96, 92, 51, 139, 62, 80, 111, 105, 88, 117, 51, 50, 69, 105, 154, 108, 115, 147, 79, 52, 101, 138, 117, 95,
           94, 57, 99, 138, 123, 141, 62, 70, 104, 86, 50, 80, 107, 100, 82, 114, 141, 135, 140, 83, 83, 90, 62, 142,
           117, 136, 110, 143, 146, 62, 73, 70, 77, 56, 109, 131, 80, 131]

df = pd.DataFrame({'Name': ["".join(np.random.choice(list('TUVWXYZ'), 5)) for _ in heights],
                   'Height': heights,
                   'Weight': weights})

ax = df.plot(x=1, y=2, marker='D', markersize=4, ls='')
mplcursors.cursor(hover=True).connect('add', show_info)

plt.show()

mplcursors example

Upvotes: 1

Related Questions