Matplotlib 中的日期与时间间隔绘图 [英] Date versus time interval plotting in Matplotlib

查看:218
本文介绍了Matplotlib 中的日期与时间间隔绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pyplot plot_date函数期望以特定的线条样式绘制日期和值对.是否有推荐的方法来针对日期/时间值绘制多个值或间隔数据?

The pyplot plot_date function expects pairs of dates and values to be plotted with a certain line style. Is there a recommended approach to plot multiple values or interval data against date/time values?

推荐答案

要绘制区间数据,您可以使用 errorbar() 函数提供的误差条并使用 axis.xaxis_date() 使 matplotlib 像 plot_date() 函数那样格式化轴.

To plot interval data, you may use the error bar provided by the errorbar() function and the use axis.xaxis_date() to make matplotlib format the axis like plot_date() function does.

这里是一个例子:

#!/usr/bin/python

import datetime
import numpy as np
import matplotlib.dates as mdates
import matplotlib.pyplot as plt

# dates for xaxis
event_date = [datetime.datetime(2008, 12, 3), datetime.datetime(2009, 1, 5), datetime.datetime(2009, 2, 3)]

# base date for yaxis can be anything, since information is in the time
anydate = datetime.date(2001,1,1)

# event times
event_start = [datetime.time(20, 12), datetime.time(12, 15), datetime.time(8, 1,)]
event_finish = [datetime.time(23, 56), datetime.time(16, 5), datetime.time(18, 34)]

# translate times and dates lists into matplotlib date format numpy arrays
start = np.fromiter((mdates.date2num(datetime.datetime.combine(anydate, event)) for event in event_start), dtype = 'float', count = len(event_start))
finish = np.fromiter((mdates.date2num(datetime.datetime.combine(anydate, event)) for event in event_finish), dtype = 'float', count = len(event_finish))
date = mdates.date2num(event_date)

# calculate events durations
duration = finish - start

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# use errorbar to represent event duration
ax.errorbar(date, start, [np.zeros(len(duration)), duration], linestyle = '')
# make matplotlib treat both axis as times
ax.xaxis_date()
ax.yaxis_date()

plt.show()

这篇关于Matplotlib 中的日期与时间间隔绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆