matplotlib畫時間(小時為間隔)序列座標
阿新 • • 發佈:2019-02-02
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
dates = ['2016010106','2016010107','2016010108','2016010109','2016010110','2016010111','2016010112','2016010113',
'2016010114','2016010115','2016010116','2016010117','2016010118']
#把string格式的日期轉換成datetime格式
xs = [datetime.strptime(d, '%Y%m%d%H' ) for d in dates]
ys = ['36','29','26','22','29','38','48','55','56','60','55','48','51']
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
#指定X軸的以日期格式(帶小時)顯示
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y%m%d%H'))
#X軸的間隔為小時
ax.xaxis.set_major_locator(mdates.HourLocator())
plt.plot(xs, ys)
plt.gcf().autofmt_xdate()
plt.show()
執行結果如下:
**如果天為間隔,修改如下:
xs = [datetime.strptime(d, ‘%Y%m%d%H’).date() for d in dates]
ax.xaxis.set_major_formatter(mdates.DateFormatter(‘%Y%m%d’))
ax.xaxis.set_major_locator(mdates.DayLocator())**