从日期序号数组设置日期刻度标签

Setting up date tick labels from a date ordinal array

我有一个从日期时间模块中提取的日期序号的一维数组。该数组将序数保存为浮点数。

我使用 matplotlib pyplot 绘制了一个图形:

import numpy as np
from datetime import datetime as dt
from matplotlib import pyplot as plt

f = plt.plot(newdates, surge)

newdates 和 surge 一维数组的大小相同。我想知道如何将日期标记设置为日期而不是日期序号。例如 newdates[0] = array([710397.]) 所以在我的图中,第一个刻度为 710397,但我希望日期为 %m%Y 格式。有没有办法直接做到这一点?附上我的图供参考。

see my figure here

假设这与 your other question 相关,我建议您根本不要使用序数。您可以简单地使用 datetime 对象并适当地格式化绘图:

from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# some dummy data...
data_to_plot = np.array([1,3,2,4]) 

# taken from the linked question:
yr = np.array([1946, 1946, 1946, 1946], dtype=np.int)
mon = np.array([1, 1, 1, 1], dtype=np.int)
day = np.array([1, 1, 1, 1], dtype=np.int)
hr = np.array([1, 2, 3, 4], dtype=np.int)
# cast year/month/day/hour to datetime object:
newdates = [datetime(y,m,d,h) for y, m, d, h in zip(yr, mon, day, hr)]

# examplary plot
fig, ax = plt.subplots(1)
plt.plot(newdates, data_to_plot)
# format the tick labels:
xfmt = mdates.DateFormatter('%Y-%m-%d %H h')
ax.xaxis.set_major_formatter(xfmt)
# make one label every hour:
hours = mdates.HourLocator(interval = 1)
ax.xaxis.set_major_locator(hours)
# rotate the labels:
plt.xticks(rotation=45)
# adjust the canvas so that the labels are visible:
plt.subplots_adjust(top=0.90, bottom=0.22, left=0.10, right=0.9)
plt.show()