【问题标题】:convert datetime to number for matplotlib datetime xaxis将日期时间转换为 matplotlib 日期时间 xaxis 的数字
【发布时间】:2022-01-23 06:12:53
【问题描述】:

如何将日期时间转换为 matplotlib 的 x 轴使用的浮点表示? matplotlib.dates.date2num 似乎无法按以下方式工作...

import pandas as pd
import matplotlib as mpl
import datetime

idx = pd.DatetimeIndex(
    [
        '2021-12-21 10:25:00+00:00', '2021-12-21 10:30:00+00:00',
        '2021-12-21 10:35:00+00:00', '2021-12-21 10:40:00+00:00',
        '2021-12-21 10:45:00+00:00', '2021-12-21 10:50:00+00:00',
        '2021-12-21 10:55:00+00:00', '2021-12-21 11:00:00+00:00',
        '2021-12-21 11:05:00+00:00', '2021-12-21 11:10:00+00:00'
    ],
    dtype='datetime64[ns, Europe/London]',
    name='time',
    freq=None
)
s = pd.Series(
    [0.6, 1.8, 2.7, 1.8, 1.5, 2.1, 0.9, 1.8, 3.2, 4.4],
    index=idx
)

fig, ax = plt.subplots()
s.plot(ax=ax)

target_x = datetime.datetime(2021, 12, 21, 18)
target_y = 2

ax.scatter(mpl.dates.date2num(target_x), target_y, marker='x')

问题似乎出在这里:

>>> ax.get_xlim()
(27334705.0, 27334750.0)

>>> mpl.dates.date2num(target_x)
18982.75

参考文献

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

现在是 Epochs / 60。

>>> ax.get_xticklabels()
[Text(27334705, 0, '10:25'),
 Text(27334740, 0, '11:00'),
 Text(27334750, 0, '11:10')]

所以我注意到 matplotlib 表示中的数字之间的差异等于日期时间之间的分钟差异。然后就可以确认了

>>> idx[7].timestamp() / 60 #'2021-12-21 11:00:00+00:00'
27334740.0

它检查出来。
我不知道这背后的原因,或者更漂亮的方法 - 只是注意到这种关系。

下面的代码标记 - 必须将时区信息添加到您的目标日期时间:

import pandas as pd
import matplotlib as mpl
import datetime
import pytz

idx = pd.DatetimeIndex(
    [
        '2021-12-21 10:25:00+00:00', '2021-12-21 10:30:00+00:00',
        '2021-12-21 10:35:00+00:00', '2021-12-21 10:40:00+00:00',
        '2021-12-21 10:45:00+00:00', '2021-12-21 10:50:00+00:00',
        '2021-12-21 10:55:00+00:00', '2021-12-21 11:00:00+00:00',
        '2021-12-21 11:05:00+00:00', '2021-12-21 11:10:00+00:00'
    ],
    dtype='datetime64[ns, Europe/London]',
    name='time',
    freq=None
)
s = pd.Series(
    [0.6, 1.8, 2.7, 1.8, 1.5, 2.1, 0.9, 1.8, 3.2, 4.4],
    index=idx
)

fig, ax = plt.subplots()
s.plot(ax=ax)

target_x = datetime.datetime(2021, 12, 21, 11, 0, 0, 0, pytz.UTC)
target_y = 2

ax.scatter(int(target_x.timestamp()/60), target_y, marker='x')

【讨论】:

  • 好地方!另一条评论是我在pandas 中注意到它有时可以根据轴将日期标准化为target_x.timestamp()/60/60/24target_x.timestamp()/60/60
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 2015-09-17
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
相关资源
最近更新 更多