python - Time format on x axis in Matplotlib
问题描述
The time on the x-axis must be represented with a time interval of 3 seconds but the increment of time in my data is 2 seconds. So, I tried to do that as demonstrated in the code, but I’m getting the time demonstrated until 09:56:09 though the time goes till 09:56:22.
Note that, the time should be start from 09:56:00
How can be the time on the x-axis completely demonstrated?
Code:
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()
解决方案
问题出for loop
在len(the_date)
. 在您的代码中添加此部分:
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):
推荐阅读
- javascript - React JS - 自动添加行
- swift - Cocoa:如何取消归档具有归档属性的 NSMutableAttributedString?
- android - 如何将变量转换为常量
- jestjs - 为什么 .mock.instances 打印这个?
- google-play - 在 google play 的主搜索中找不到应用程序
- bash - 如有必要,使用 sed 添加子网掩码格式化 IP 地址列表
- c# - 在 Windows 窗体项目的 Main 中初始化 Class Form 实例的原因是什么?
- android - 如何将基于 Cradle 的 Android Studio 项目导入 Visual Studio 2017 或 2019?
- rust - 如何为 i686 应用程序链接 user32.lib (Windows)
- .net - MSK 触发器的 AWS Lambda 事件负载