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

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

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

enter image description here 输出:数据坐标736772.234764 1.623170

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

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

最佳答案

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

Matplotlib represents dates using floating point numbers specifying the number of days since 0001-01-01 UTC, plus 1.
For example, 0001-01-01, 06:00 is 1.25, not 0.25. Values < 1, i.e. dates before 0001-01-01 UTC are not supported.

要将此数字转换为日期时间,请使用matplotlib.dates.num2date()

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

关于python - 来自事件坐标的 Matplotlib 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49267011/

相关文章:

python - 指定要在 Django 中使用的数据库

python - 在 Jupyter Notebook 中增加 Matplotlib .show() 的 DPI

python - 在 python 中缩放 imread 矩阵

python - 为什么 pyplot 方法可以立即应用,而子图轴方法则不能?

python - Scala/Python 中这两个映射表达式有什么区别?

python - Tensorflow 估计器 : Cache bottlenecks

python - 两个元组作为Python列表中的一个元素

python - PANDAS:int32溢出?无法建立枢纽分析表

python - 创建绘图的 Pytest 测试函数

python-3.x - 将 matplotlib 图像发送到 pymsteams(无法创建新标签 pymsteams)