简体   繁体   English

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

[英]Matplotlib datetime from event coordinates

I'm sure this is a duplicate of some other question somewhere, but I'm not able to find any answer... so sorry for that, any link would also be apprechiated ;) 我确定这是某个地方的其他问题的重复,但我找不到任何答案...对此感到抱歉,任何链接也将被理解;)

I have the x-axis as datetime and would like to get the datetime where a click happened. 我将x轴设置为datetime,并希望获得单击发生的日期时间。 instead I get some coordinates which I do not understand. 相反,我得到了一些我不理解的坐标。 How do I convert these coordinates into a datetime (str)? 如何将这些坐标转换为日期时间(str)?

Consider the following example: 考虑以下示例:

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()

You can click at the plot and it will open a yellow pop-up showing the informations of the selected point. 您可以单击该图,它会打开一个黄色弹出窗口,显示所选点的信息。 Moreover, the classical way to connect a function to matplotlib prints the current coordinates. 此外,将函数连接到matplotlib的经典方法会打印当前坐标。

在此处输入图片说明 Output: data coords 736772.234764 1.623170 输出: data coords 736772.234764 1.623170

Note: the displayed value t: 736772.230336 is almost the same as event.xdata (736772.234764) in the connected function. 注意:显示的值t: 736772.230336与所连接函数中的event.xdata (736772.234764)几乎相同。 I would assume, mpldatacursor takes just the coordinates of the closest datapoint. 我认为, mpldatacursor仅采用最接近的数据点的坐标。

How do I convert that value into a string of the form '%Y-%m-%d %H:%M:%S' ? 如何将该值转换为'%Y-%m-%d %H:%M:%S'形式的字符串?

The units of the matplotlib plot are days since the year one (plus one day). matplotlib图的单位是从第一年起的天数(加上一日)。 As the documentation tells us: 文档所示

Matplotlib represents dates using floating point numbers specifying the number of days since 0001-01-01 UTC, plus 1. Matplotlib使用浮点数字表示日期,该数字指定从0001-01-01 UTC开始的天数加1。
For example, 0001-01-01, 06:00 is 1.25, not 0.25. 例如,0001-01-01、06:00是1.25,而不是0.25。 Values < 1, ie dates before 0001-01-01 UTC are not supported. 不支持小于1的值,即0001-01-01 UTC之前的日期。

To convert this number to datetime use matplotlib.dates.num2date() . 要将这个数字转换为datetime使用matplotlib.dates.num2date()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM