matplotlib 如何在x轴上正确显示时间刻度?

mrzz3bfm  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(193)

下面是我读取日志文件并以直方图显示数据的代码

import cv2
import os
import sys
import time
import matplotlib.pyplot as plt

os.chdir('C:/Users/User/anaconda3/envs/yolov7_custom/yolov7-main')

number=[]
times=[]

f=open('log.txt','r')
for row in f:
    row=row.strip().split(' ')
    if row[0] != '' :
    number.append(int(row[0]))
    row5=row[5].split(':')
    times.append(int(row5[0])*100+int(row5[1]))


plt.bar(times,number,color='g',label='File Time')
plt.xlabel('Time', fontsize=12)
plt.ylabel('Number of people', fontsize=12)

plt.show()

显示本附件Histogram of people vs time的结果
从此日志文件中提取信息后

6    03/04/2023 22:13:20
2    03/04/2023 22:14:57
12    03/04/2023 22:18:24
15    03/04/2023 22:20:01
18    03/04/2023 22:21:41
11    03/04/2023 22:23:16
19    03/04/2023 22:24:51
17    03/04/2023 22:26:29
15    03/04/2023 22:28:04
17    03/04/2023 22:29:42
17    03/04/2023 22:31:17
15    03/04/2023 22:32:51
19    03/04/2023 22:34:25
15    03/04/2023 22:36:00
15    03/04/2023 22:37:34
20    03/04/2023 22:39:08
17    03/04/2023 22:40:44

11    03/04/2023 21:47:24
11    03/04/2023 21:48:00

由于x轴是24小时制,所以在x轴上显示2180这样的数字是没有意义的,这样会造成数据的空白(2140之后,x轴上的下一个数字应该是2200),我可以用什么方法来解决这个问题?

4xy9mtcn

4xy9mtcn1#

找到了这个链接Python Mathplotlib: x-axis scale for 24 hours based on 5 minute timestamps for that day的答案,并复制了代码,以获得我想要的。只需创建一个24小时标签,是与分钟使用np。linspace函数。转换成分钟的时间,酒吧(时间)将按比例计算的分钟值。

import cv2
import os
import sys
import time
import matplotlib.pyplot as plt
import numpy as np

os.chdir('C:/Users/User/anaconda3/envs/yolov7_custom/yolov7-main')
x=np.linspace(0,1440,13)
time_labels = ["00:00", "02:00", "04:00", "06:00", "08:00", "10:00", "12:00", 
"14:00", "16:00", "18:00", "20:00", "22:00", "24:00"]
number=[]
times=[]

f=open('log.txt','r')
for row in f:
    row=row.strip().split(' ')
    if row[0] != '' :
    number.append(int(row[0]))
    row5=row[5].split(':')
    times.append(int(row5[0])*60+int(row5[1]))

plt.bar(times,number,color='g',label='File Time')
plt.xlabel('Time', fontsize=12)
plt.ylabel('Number of people', fontsize=12)
plt.xticks(x, labels=time_labels, rotation='vertical') 
plt.show()

Graph showing 24hr time scale

相关问题