如何將日期時間轉換為 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
參考
- 在日期時間、時間戳和日期時間 64 之間轉換
- Python matplotlib.dates.date2num:將 numpy 陣列轉換為 matplotlib 日期時間
uj5u.com熱心網友回復:
這是紀元/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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394399.html
標籤:Python 熊猫 matplotlib
上一篇:Python排序可視化
