python - Matplotlib 中 x 轴上的时间格式

标签 python python-3.x matplotlib plot

x 轴上的时间必须用 3 秒的时间间隔来表示,但我的数据中时间的增量是 2 秒。因此,我尝试按照代码中的演示进行操作,但我得到的演示时间一直到 09:56:09,尽管时间一直到 09:56:22。

注意,时间应该从09:56:00开始

x轴上的时间如何才能完整显示出来?

代码:

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

SO=[100,300,600,800,850,310,560,790,500,810,790,490];the_date_0=['01-02-2018 09:56:00.0000','01-02-2018 09:56:02.0000',
                                                               '01-02-2018 09:56:04.0000','01-02-2018 09:56:06.0000',
                                                               '01-02-2018 09:56:08.0000','01-02-2018 09:56:10.0000',
                                                               '01-02-2018 09:56:12.0000','01-02-2018 09:56:14.0000',
                                                               '01-02-2018 09:56:16.0000','01-02-2018 09:56:18.0000',
                                                               '01-02-2018 09:56:20.0000','01-02-2018 09:56:22.0000']

the_date=[]
Date_axis=[]

for i in the_date_0:
    the_date.append(time.mktime(time.strptime(i, "%d-%m-%Y %H:%M:%S.0000")))

for i1 in range(0,len(the_date),3):
    time1=datetime.fromtimestamp(time.mktime(time.strptime("01-02-2018 09:56:00.0000", "%d-%m-%Y %H:%M:%S.0000")))+timedelta(seconds=i1)
    Date_axis.append(time.mktime(time1.timetuple()))

fig = plt.figure()
dateconv=np.vectorize(datetime.fromtimestamp)
Date_F=dateconv(the_date)
Date_axis_ok=dateconv(Date_axis)
ax1 = plt.subplot2grid((1,1), (0,0))
ax1.plot_date(Date_F,SO,'r-',label='the values')
ax1.set_yticks(range(0,1000,100))
ax1.set_xticks(Date_axis_ok)
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
for label in ax1.xaxis.get_ticklabels():
    label.set_rotation(45)
ax1.grid(True)
plt.legend()
plt.show()

图表 enter image description here

最佳答案

问题出在 len(the_date) 中的 for 循环 中。 在您的代码中添加此部分:

from datetime import datetime, timedelta, date
duration = datetime.combine(date.min, datetime.strptime(the_date_0[-1], "%d-%m-%Y %H:%M:%S.0000").time()) - datetime.combine(date.min, datetime.strptime(the_date_0[0], "%d-%m-%Y %H:%M:%S.0000").time())
seconds = int(duration.total_seconds())

并以这种方式修改循环:

for i1 in range(0,seconds,3):

输出: enter image description here

关于python - Matplotlib 中 x 轴上的时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50772954/

相关文章:

python - python中mf4到csv的转换

python - 检查一列中的值是否在另一列的列表中

python - 两个变量变成1个变量

matplotlib:图例标题的对齐

python - 如何使用 paramiko.RSAKey.from_private_key()?

python - statsmodels:用于生成分位数回归系数置信区间的方法?

python-3.x - 我应该使用 tf.add 还是 + 在 Tensorflow 中添加两个张量?

python - 为什么在不同的 python 版本上运行相同的代码会得到不同的输出?

python - 让 set_under 和 set_bad 在 matplotlib contourf plot 中工作

python - 线性 curve_fit 总是产生 1 的斜率和 y 轴截距