2016-11-23 56 views
2

這可能是類似於此problem但礦是plot_date的上下文中。轉換s到H:在matplotlib(data_plot)在y軸米

UPDATE

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

是樣本輸出:

enter image description here

我想要顯示的y軸在H:米格式。

+0

[Python的時間秒至h:M:S]的可能的複製(http://stackoverflow.com/questions/775049/python-time-seconds-to-hms) – Jalo

+0

燦你詳細說明Jalo。謝謝。 – user1693411

+0

好的。但我需要更多有關你的代碼,因爲我無法重現你的情節,爲了增加改進 – Jalo

回答

1

這裏是一個可行的解決方案。因爲我不知道數據庫如何涉及值days3time3我忽略了這一部分。該time3以秒爲單位,但是,plot_dates需要datetime -objects,所以我們需要轉換,第一。的days3格式不實用,所以我創建由這些值各自datetime對象。

在繪圖中,設置DateFormatter呼叫plot_dates是至關重要的。

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

enter image description here

+0

謝謝你,但最後一件事,我如何解釋AM和PM?或者它以24格式轉換。 – user1693411

+0

明白了!合掌! – user1693411