来自事件坐标的 Matplotlib 日期时间

Sno*_*ing 2 python matplotlib

我确信这与其他地方的其他问题重复,但我找不到任何答案......对此感到抱歉,任何链接也将受到赞赏;)

我将 x 轴作为日期时间,并希望获取发生点击的日期时间。相反,我得到了一些我不明白的坐标。如何将这些坐标转换为日期时间 (str)?

考虑以下示例:

import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
import mpldatacursor        # pip install mpldatacursor

df = pd.DataFrame(index=[dt.datetime.now() + dt.timedelta(i) for i in range(20)], 
                  data={'val1': [10/(i+1) for i in range(20)],
                        'val2': [5 * 2**(-i) for i in range(20)]})
fig, ax = plt.subplots()
df.plot(ax=ax)

# mpldatacursor opens a dragable yellow rectangle with the informations
# for that point. The kwargs `x` and `y` seem to be the coords.
def myformatter(**kwargs):
    # For one dataset it worked specifying `unit='m'`, coincidence?
    kwargs['x2'] = pd.to_datetime(kwargs['x']).strftime('%Y-%m-%d %H:%M:%S')
    kwargs['x3'] = pd.to_datetime(kwargs['x'], unit='m').strftime('%Y-%m-%d %H:%M:%S')
    kwargs['x4'] = pd.to_datetime(kwargs['x'], unit='h').strftime('%Y-%m-%d %H:%M:%S')
    label = ('t: {x}\nt(ns): {x2}\nt(m): {x3}\nt(h): {x4}\ny: {y:.10}'.format(**kwargs))
    return label
mpldatacursor.datacursor(axes=ax, formatter=myformatter,
                         bbox=dict(fc='yellow', alpha=0.75), draggable=True)

# To compare the coords.
def onclick(event):
   print('data coords %f %f' % (event.xdata, event.ydata))
plt.connect('button_press_event', onclick)

plt.show()
Run Code Online (Sandbox Code Playgroud)

您可以单击该图,它将打开一个黄色弹出窗口,显示所选点的信息。此外,将函数连接到 matplotlib 的经典方法会打印当前坐标。

在此输入图像描述 输出:data coords 736772.234764 1.623170

注意:显示的值与连接函数中的值t: 736772.230336几乎相同。event.xdata (736772.234764)我假设,mpldatacursor仅采用最近数据点的坐标。

如何将该值转换为以下形式的字符串'%Y-%m-%d %H:%M:%S'

Imp*_*est 5

matplotlib 图的单位是自第一年以来的天数(加上一天)。正如文档告诉我们的:

Matplotlib 使用浮点数表示日期,指定自 0001-01-01 UTC 以来的天数加 1。
例如,0001-01-01, 06:00 是 1.25,而不是 0.25。值 < 1,即不支持 0001-01-01 UTC 之前的日期。

将此数字转换为datetime使用matplotlib.dates.num2date().

d = 736772.230336
matplotlib.dates.num2date(d).strftime('%Y-%m-%d %H:%M:%S')
# '2018-03-19 05:31:41'
Run Code Online (Sandbox Code Playgroud)