Python Forum
Matplotlib Hovering Event displaying (x, y) data - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Matplotlib Hovering Event displaying (x, y) data (/thread-21875.html)



Matplotlib Hovering Event displaying (x, y) data - RawlinsCross - Oct-18-2019

Hey, I'm an Unladed Swallow - how bout that!. Anyhooo….I have an excel graph that has x data in column A starting in row 7 and several columns of y data. I search out a given column through a unique identifier and do an x,y scatter plot. The thing is I want to be able to hover on a point and for it to show the x,y data.

I recently found an article on another forum that does something similar
https://stackoverflow.com/questions/7908636/possible-to-make-labels-appear-when-hovering-over-a-point-in-matplotlib

I'm trying to adapt that code to mine and I'm having a rough time. Here's what I have done so far. Think the problem is in the list of lists? Not sure, new to python.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np; np.random.seed(1)
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# Excel graph stored on a desktop
data = pd.read_excel(r'c:/Users/jhalfyard/Desktop/HydroMetPro.xlsx')
sDataIdentifier = 'Aqu_223-IR2-FEED_Co'
lastrow = data.shape[0]
diloc = data.columns.get_loc(sDataIdentifier)
# Data starts on row 7
x = data.iloc[7:lastrow, 0]
y = data.iloc[7:lastrow, diloc]
names = np.array(list("A")*(data.shape[0] - 7))

fig, ax = plt.subplots()
sc = plt.scatter(x, y, s=5, color='blue')
fig.autofmt_xdate()  # Rotates and auto-formats the date
fig.canvas.set_window_title(sDataIdentifier)  # Sets the figure title
ax.set_ylabel('Concentration (mg/L)')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b-%y'))

annot = ax.annotate("", xy=(0,0), xycoords='data', xytext=(15,15), textcoords="offset points",
                    bbox=dict(boxstyle="round", fc='white'),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)


def update_annot(ind):
    print(ind)
    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(",".join(list(map(str,y))),
                          "".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_alpha(1.0)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()


fig.canvas.mpl_connect("motion_notify_event", hover)

plt.subplots_adjust(top=0.95, bottom=0.16)  # Adjust the top of the graph (default = 0.90)
plt.show()