为什么 x 坐标是时间戳列表,当鼠标移动(悬停)时不在 matplotlib 中显示为坐标?

why x coordinates that's a list of timestamp, don't show as coordinates in matplotlib when mouse moves(hover)?

它也没有显示在右下角。数据来自数据库中的 table。它很好地绘制了图表,但鼠标悬停在图表上时 x 的坐标丢失了。请帮忙。 我正在使用 mplcursors 进行鼠标悬停。

import matplotlib.pyplot as plt
import mplcursors
from datetime import datetime

ax1 = plt.subplot(111)
time = ['2017-01-01 09:00:00.000', '2017-01-01 09:00:01.000', '2017-01-01 09:00:02.000', '2017-01-01 09:00:03.000', '2017-01-01 09:00:04.000', '2017-01-01 09:00:05.000', '2017-01-01 09:00:06.000', '2017-01-01 09:00:07.000', '2017-01-01 09:00:08.000', '2017-01-01 09:00:09.000', '2017-01-01 09:00:10.000']
lstDateTime = [str(datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f').isoformat(sep=' ', timespec='milliseconds')) for x in
               time]
print(f'lstDateTime: {", ".join(lstDateTime)}')
bet = [60.01, 60.01, 62.01, 61.01, 63.79, 69.28, 63.51, 62.24, 60.53, 61.53, 60.53]
prob = [61.1, 61.2, 63.03, 62.03, 64.02, 70.28, 64.51, 63.24, 61.53, 62.53, 61.53]
plt.plot_date(lstDateTime, bet, "b-", label="bet")
plt.plot_date(lstDateTime, prob, "g-", label="porb")
plt.tick_params(axis='x', rotation=90)
# ax1.plot(lstDateTime, bet, "b-", label="bet")
# ax1.plot(lstDateTime, prob, "g-", label="porb")
# ax1.tick_params(axis='x', rotation=90)
mplcursors.cursor(hover=True)
plt.show()

困扰我的是,从一开始我什至在 matplotlib 卡的右下角也看不到 x 坐标。

这是我不明白的事情。 x 轴有时间戳列表。

'2017-01-01 11:43:07.000', '2017-01-01 11:43:23.000', '2017-01-01 11:42:45.000' 

喜欢这个但是没有出现。我需要知道为什么以及如何纠正它。

问题出在这里:- 问题是时间转换。

lstDateTime = [str(datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f').isoformat(sep=' ', timespec='milliseconds')) for x in time] print(f'lstDateTime: {", ".join(lstDateTime)}')

但它给出了正确的格式问题是 x 坐标停止显示。

怎么样。 您可能必须使用 matplotlib dates.

但是精度好像有问题,看hover标签。有一个不在数据中的时间戳。

import matplotlib.pyplot as plt
import mplcursors
from datetime import datetime

import matplotlib.dates as mdates
mdates.date2num

fig, ax = plt.subplots()
time = ['2017-01-01 09:00:00.000', '2017-01-01 09:00:01.000', '2017-01-01 09:00:02.000', '2017-01-01 09:00:03.000', '2017-01-01 09:00:04.000', '2017-01-01 09:00:05.000', '2017-01-01 09:00:06.000', '2017-01-01 09:00:07.000', '2017-01-01 09:00:08.000', '2017-01-01 09:00:09.000', '2017-01-01 09:00:10.000']

# to not use isoformat, use datetime objects
lstDateTime = [datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f') for x in
               time]

# convert to matplotlib date format
lstDateTime = mdates.date2num(lstDateTime)

#print(f'lstDateTime: {", ".join(lstDateTime)}')
bet = [60.01, 60.01, 62.01, 61.01, 63.79, 69.28, 63.51, 62.24, 60.53, 61.53, 60.53]
prob = [61.1, 61.2, 63.03, 62.03, 64.02, 70.28, 64.51, 63.24, 61.53, 62.53, 61.53]
ax.plot_date(lstDateTime, bet, "b-", label="bet")
ax.plot_date(lstDateTime, prob, "g-", label="porb")
plt.tick_params(axis='x', rotation=90)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S.%f'))

fig.autofmt_xdate()
mplcursors.cursor(hover=True)

plt.show()