请注意,在示例中没有给出数字时间戳。Matplotlib 将它们解释为文本标签并将它们编号为 0,1,2,...,N-1。另请注意,时间间隔不相等,但 matplotlib 会在 x 轴上均匀地显示精确的 x 标签。
要显示 x 轴,显式注释函数可以解释数字 x 坐标(在 0 到 N-1 范围内),将其四舍五入并将其用作字符串列表的索引。在这种情况下,x 坐标将显示最近的 x 标签,而 y 值将被很好地插值。
这是一些示例代码:
from matplotlib import pyplot as plt
import mplcursors
def show_annotation(sel):
xi, yi = sel.target
xi = int(round(xi))
sel.annotation.set_text(f'{x[xi]}\nvalue:{yi:.3f}')
x = ['22-02 11:16:15', '22-02 15:31:54', '22-02 15:32:30',
'22-02 15:32:45', '22-02 15:33:57', '22-02 15:34:13',
'22-02 15:34:46']
y = [1, 4, 3, 4, 8, 9, 2]
figure, ax = plt.subplots()
dt = ax.plot(x, y)
cursor = mplcursors.cursor(dt, hover=True)
cursor.connect('add', show_annotation)
figure.tight_layout()
figure.autofmt_xdate() # has no effect, because matplotlib only encountered texts for the x-axis
plt.show()

如果您还需要 x 的完全插值时间戳,则应将 x 转换x
为数字时间戳。还要小心提供年份,因为默认年份是 1901,这可能会在闰年期间引起冲突。
在下面的示例代码中,第一个时间戳被修改为与其余时间戳一起使用。该图现在使用与时间成比例的距离。
from matplotlib import pyplot as plt
from matplotlib import dates as mdates
import mplcursors
from datetime import datetime
def show_annotation(sel):
xi, yi = sel.target
sel.annotation.set_text(f"{mdates.DateFormatter('%d %b %H:%M:%S')(xi)}\nvalue:{yi:.3f}")
x = ['22-02 15:31:15', '22-02 15:31:54', '22-02 15:32:30',
'22-02 15:32:45', '22-02 15:33:57', '22-02 15:34:13',
'22-02 15:34:46']
# first, convert the strings to datetime objects, and then convert to a numerical time
# as the day is put before the month, a specific format conversion needs to be supplied
# the year needs to be prepended to get the timestamps in the correct year
x = [mdates.date2num(datetime.strptime('2020-'+xi, '%Y-%d-%m %H:%M:%S')) for xi in x]
y = [1, 4, 3, 4, 8, 9, 2]
figure, ax = plt.subplots()
dt = ax.plot(x, y)
ax.xaxis_date()
# display the time on two lines: the day and the shortened month name, and then HH:MM:SS
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d %b\n%H:%M:%S'))
# ax.set_xticks(x) # to set the input time stamps as xticks
figure.tight_layout()
cursor = mplcursors.cursor(dt, hover=True)
cursor.connect('add', show_annotation)
plt.show()
