joferkington / mpldatacursor

Interactive "data cursors" (a.k.a. annotation pop-ups) for matplotlib
MIT License
194 stars 47 forks source link

How to extract date on X axis from a point on chart #87

Open baderAmmoun opened 5 years ago

baderAmmoun commented 5 years ago

I need to access the date form x axis once the mouse hovering of the representative point on the plot. Now the only thing I get when I apply the callback function is the coordinate of the figure

joferkington commented 5 years ago

For date axes, matplotlib uses an internal representation of dates. The original datetime instances are converted into this floating-point-based date representation. You can convert the coordinates you're getting back into a datetime with matplotlib.dates.num2date. As an example:

import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

from mpldatacursor import datacursor

def callback(**kwargs):
    """Display the day of the week and y-value instead of the full date."""
    d = mdates.num2date(kwargs['x']) # Datetime instance
    day = d.strftime('%I%p %a').lstrip('0')
    return 'Time: {}\n Y: {:0.2f}'.format(day, kwargs['y'])

# Make an example plot...
t = mdates.drange(dt.datetime(2014, 1, 15), dt.datetime(2014, 2, 27),
                          dt.timedelta(hours=2))
y = np.sin(t)
fig, ax = plt.subplots()
ax.plot_date(t, y, 'b-')
fig.autofmt_xdate()

# Now we'll use our custom function and turn things back into a datetime
datacursor(formatter=callback)

plt.show()

Hope that helps!

baderAmmoun commented 5 years ago

yes thanks . one last question how can I customize the parameters that I need to pas to callback function