6

I have data in iPython DataFrame like this

    Date                        X           Y           Z
0   2015-11-30 20:23:05.556     281.764900  -43.895060  8.714666
1   2015-11-30 20:23:05.757     192.519990  -44.636436  1.720552
2   2015-11-30 20:23:05.958     149.030600  -45.098050  1.958352
3   2015-11-30 20:23:06.171     140.707600  -44.622448  1.510729
4   2015-11-30 20:23:06.366     139.154890  -45.154003  4.783974
5   2015-11-30 20:23:06.564     138.875140  -44.790306  2.266093

The dtypes of the columns are these:

Date    datetime64[ns]
X              float64
Y              float64
Z              float64
dtype: object

I set the button_press_event to my fig like this

def onclick(event):
    print 'button=%d, x=%d, y=%d, xdata=%s, ydata=%f'%(
        event.button, event.x, event.y, event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('button_press_event', onclick)

and I want to get data from x axes in Date format or String format, but after click in graph I have just this

button=1, x=152, y=339, xdata=735932.856811, ydata=8.518828

How to set output from xdata in String?

2 Answers 2

5

Matplotlib's date support pre-dates numpy's datetime support (and predates pandas entirely). Therefore, it uses its own internal date convention.

To convert the "raw" number you're getting back to a datetime, use matplotlib.dates.num2date.

As an example similar to what you're doing:

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

import matplotlib.dates as mdates

def on_click(event):
    if event.inaxes is not None:
        print mdates.num2date(event.xdata)

t = pd.date_range('2015-11-01', '2016-01-06', freq='H')
y = np.random.normal(0, 1, t.size).cumsum()

df = pd.DataFrame({'Y':y}, index=t)

fig, ax = plt.subplots()
df.plot(ax=ax)
fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
Sign up to request clarification or add additional context in comments.

2 Comments

So actually the solution was just put mdates.num2date(event.xdata) instead of event.xdata. Thank you very much!
45 min of search internet to find this answer! Thank you!
1

The answer from @Joe Kington is not ideal for this situation. This answer is a working solution to this problem (returned a very large number in event.xdata in matplotlib click event when plotting with pandas.plot): https://stackoverflow.com/a/54036315/8564548 Pandas themself solve the solution with this link

pd.Period(ordinal=int(event.xdata), freq=freq)

where freq is the freq of your plot, could be something like '1s', '1min', '1H'... etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.