Skip to main content
 首页 » 编程设计

python之将 s 转换为 h :m in y-axis in matplotlib (data_plot)

2025年02月15日17exmyth

这可能类似于此 problem但我的是在 plot_date 的上下文中。

更新

log = row[3] 
 
day = log.strftime("%Y%m%d") 
month = log.strftime("%m") 
month2 = log.strftime("%B") 
year = log.strftime("%y") 
times = to_seconds(log.strftime("%I:%M")) 

log 来自数据库记录,格式为2016-10-28 20:53:26。

time3 =[29100.0, 28860.0, 29280.0, 37980.0, 29100.0, 24780.0, 29700.0, 29160.0, 29460.0, 29100.0, 28980.0, 33780.0, 29400.0, 29100.0, 29400.0, 30360.0, 6180.0, 28860.0, 29400.0, 4440.0, 29160.0, 29160.0] 
 
day3 = ['20161003', '20161004', '20161005', '20161006', '20161007', '20161009', '20161010', '20161011', '20161012', '20161013', '20161014', '20161017', '20161018', '20161019', '20161020', '20161021', '20161023', '20161024', '20161025', '20161026', '20161027', '20161028'] 
 
plt.grid(True, which='both') 
plt.grid(b=True, which='major', color='k', linestyle='-') 
plt.grid(b=True, which='minor', color='k', linestyle='-', linewidth=0.1) 
plt.xticks(rotation='vertical',fontsize='small') 
plt.minorticks_on() 
plt.margins(0.01) 
 
plt.plot_date(x=day3,y=time3,color="red", linestyle='--', markersize=4) 
plt.ylabel("Time") 
plt.xlabel("Day") 

附件是示例输出:

我想以 H:m 格式显示 y 轴。

请您参考如下方法:

这是一个可行的解决方案。因为我不知道数据库如何与 days3 和 time3 中的值相关,所以我忽略了那部分。 time3 以秒为单位给出,但是,plot_dates 需要 datetime 对象,所以我们需要先转换它。 days3 的格式没有用,所以我根据这些值创建了相应的 datetime 对象。

在绘图中,在调用 plot_dates 之后设置 DateFormatter 是至关重要的。

import matplotlib.pyplot as plt 
import matplotlib.dates 
import datetime 
 
 
time3 =[29100.0, 28860.0, 29280.0, 37980.0, 29100.0, 24780.0, 29700.0, 29160.0, 29460.0, 29100.0, 28980.0, 33780.0, 29400.0, 29100.0, 29400.0, 30360.0, 6180.0, 28860.0, 29400.0, 4440.0, 29160.0, 29160.0] 
#time3 is in seconds, but we need it as a datetime object 
time3 = [datetime.datetime(1970,1,1) + datetime.timedelta(seconds=time) for time in time3] 
 
# days3 are some (but not all) dates in october, create datetime objects as required 
days3 = [] 
for d in range(3,29): 
    if d not in [8,15,16,22]: 
        days3.append(datetime.date(2016,10,d)) 
 
 
plt.grid(True, which='both') 
plt.grid(b=True, which='major', color='k', linestyle='-') 
plt.grid(b=True, which='minor', color='k', linestyle='-', linewidth=0.1) 
plt.xticks(rotation='vertical',fontsize='small') 
plt.minorticks_on() 
plt.margins(0.01) 
 
plt.plot_date(x=days3,y=time3,color="red", linestyle='--', markersize=4) 
plt.gca().yaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M'))  
plt.ylabel("Time") 
plt.xlabel("Day") 
plt.tight_layout() 
plt.show()