0

它也没有显示在右下角。数据来自数据库中的表。它可以很好地绘制图形,但鼠标悬停在图形上时 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()

困扰我的是,从一开始我就看不到 x 坐标,即使在 matplotlib 卡的右下角也是如此。

在此处输入图像描述

这是我不明白的事情。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 坐标停止显示。

4

1 回答 1

0

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

但是好像准确度有问题,看hover tag。有一个时间戳不在数据中。

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()

在此处输入图像描述

于 2020-04-18T15:21:12.023 回答