如何用Python以自然人类可读的方式绘制时间相关信息?
通常情况下,你会有一组与时间相关的事件,比如访问网站的次数、价格信息等等,这些事件都有一个时间值,我们可以称之为时间戳(其实日期时间对象也可以)。那么,如何将这些事件绘制出来,让时间轴上显示人们能看懂的、有意义的值,而不是单纯的秒数呢?
我在找gnuplot和matplot这两个工具,但一直没找到合适的方法。问题是,虽然matplot可以每小时设置刻度,但我觉得能在每N小时显示文本时间信息会更好,而不是让人去数小时。
我觉得gnuplot可能有点复杂,或者说并不是专门为这个设计的。有没有什么建议呢?
1 个回答
2
这里有一个简单的例子,展示了如何用非常好用且文档齐全的matplotlib库来绘制一些值和时间的关系:
data.csv: VISIT_TIME TOTAL_VISITS 06:00:00 290 06:30:00 306 07:00:00 364 07:30:00 363 08:00:00 469 08:30:00 436 09:00:00 449 09:30:00 451 10:00:00 524 10:30:00 506 11:00:00 613 11:30:00 585 12:00:00 620 12:30:00 529 13:00:00 588 13:30:00 545
这是一个简单的程序,用来说明这个概念:
import matplotlib.dates as mdates
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import datetime as dt
import sys
def main( datafile ):
np_rec_array = mlab.csv2rec( datafile, delimiter='\t' )
np_rec_array.sort() # in-place sort
# a `figure` is a starting point for MPL visualizations
fig = plt.figure( figsize=(8,6) )
# add a set of `axes` to above `figure`
ax = fig.add_subplot(111)
x = np_rec_array.visit_time
y = np_rec_array.total_visits
# `plot_date` is like `plot` but allows for easier x-axis formatting
ax.plot_date(x, y, 'o-', color='g')
# show time every 30 minutes
ax.xaxis.set_major_locator( mdates.MinuteLocator(interval=30) )
# specify time format
ax.xaxis.set_major_formatter( mdates.DateFormatter("%H:%M") )
# set x-axis label rotation (otherwise they can overlap)
for l in ax.get_xticklabels():
l.set_rotation(60)
plt.title( 'Website Visits' )
plt.show()
if __name__ == '__main__':
if len( sys.argv ) == 1:
sys.stderr.write( 'need a filename, exiting...' )
sys.exit(-1)
main( sys.argv[1] )
输出的结果是下面这张图片:
