横轴为日期的图表绘制

作者 : RY    标签: matplotlib plot_date
切换行号 全选 下载代码

演示如何使用plot_date()绘制横轴为日期的图表,可以选择以数据为刻度,或者等间距的刻度。

01# -*- coding: utf-8 -*-
02import numpy as np
03import pylab as pl
04from StringIO import StringIO
05data_str = """
062012-04-01_02 68
072012-04-01_05 70
082012-04-01_08 69
092012-04-01_11 71
102012-04-01_14 72
112012-04-01_20 70
122012-04-02_02 71
132012-04-02_05 70
142012-04-02_08 69
152012-04-02_11 71
162012-04-02_14 69
172012-04-02_20 71
182012-04-03_02 74
192012-04-03_05 73
202012-04-03_08 77
212012-04-03_11 70
222012-04-03_14 71
232012-04-03_20 70
242012-04-04_02 70
252012-04-04_05 72
262012-04-04_08 72
272012-04-04_11 69
282012-04-04_14 71
292012-04-04_20 69
302012-04-05_02 75
31"""
32 
33data = np.loadtxt(StringIO(data_str),
34        dtype=np.dtype([("t", "S13"),("v", float)]))
35         
36datestr = np.char.replace(data["t"], "_", " ")
37t = pl.datestr2num(datestr)
38v = data["v"]
39 
40pl.plot_date(t, v, fmt="-o")
41 
42pl.subplots_adjust(bottom=0.3)
43 
44ax = pl.gca()
45ax.fmt_xdata = pl.DateFormatter('%Y-%m-%d %H:%M:%S')
46pl.xticks(rotation=90)
47 
48pl.xticks(t, datestr) # 如果以数据点为刻度,则注释掉这一行
49ax.xaxis.set_major_formatter(pl.DateFormatter('%Y-%m-%d %H'))
50 
51pl.grid()
52pl.show()

loading...