Reputation: 345
If you have datetime objects on your x-axis how can you get which one was clicked on the click event handler for matplotlib?
I.e when you do this:
def onclick2(event):
print event.x
onClickId = figure.canvas.mpl_connect('button_press_event', OnClick2)
I've tried event.x, event.xdata and event._x and they all return ints
Upvotes: 4
Views: 2352
Reputation: 18246
You should use num2date(…)
to get the date back. See this answer for an example of how to use it.
Upvotes: 0
Reputation: 318
I came across a similar problem when trying to return timestamp x axis data from a pandas time-indexed data frame plotted using matplotlib. Attempting Ajean's num2date suggestion on event.xdata returns a float value that is far too large to be a date number (e.g. 23286385.16 for 2014-4-14 2:25).
To expand upon Ajean's suggestion, it is best to first convert the datetime object to a numpy.float64 using the matplotlib.dates.date2num
function. Then you may use the numpy.float64 array this created as the x-axis with the matplotlib event handler. Returned event.xdata from the event handler may then be converted back to a datetime using matplotlib.dates.num2date
function.
Upvotes: 1