条形图与timedelta作为条宽

oxt*_*tay 6 python matplotlib bar-chart dataframe pandas

我有一个pandas数据帧,其中包含一个包含timestamps(start)的列,另一列包含timedeltas(duration)以指示持续时间.

我正在尝试绘制一个条形图,在时间戳上显示这些持续时间的左边缘.无论如何我还没有在网上找到它.有没有办法实现这个目标?

到目前为止,这就是我所拥有的,它不起作用:

    height = np.ones(df.shape[0])
    width = [x for x in df['duration']]
    plt.bar(left=df['start'], height=height, width=width)
Run Code Online (Sandbox Code Playgroud)

编辑: 我已更新宽度如下,但也没有解决此问题:

width = [x.total_seconds()/(60*1200) for x in df['duration']]
Run Code Online (Sandbox Code Playgroud)

我很想知道是否datetime.timedelta可以使用对象width,因为datetime对象可以用作x轴.如果没有,有什么替代品?

编辑#2:

这可能不是我的问题的确切答案,但它解决了我的想法.对于任何有兴趣的人,这是我最终采取的方法(我为此目的使用startduration制作end):

    for i in range(df.shape[0]):
        plt.axvspan(df.ix[i, 'start'], df.ix[i, 'end'], facecolor='g', alpha=0.3)
        plt.axvline(x=df.ix[i, 'start'], ymin=0.0, ymax=1.0, color='r', linewidth=1)
        plt.axvline(x=df.ix[i, 'end'], ymin=0.0, ymax=1.0, color='r', linewidth=1)
Run Code Online (Sandbox Code Playgroud)

Pri*_*mer 3

如果您的类型df.duration[0]pandas.tslib.Timedelta并且您的timestamps距离相隔几天,您可以使用:

width = [x.days for x in df.duration]
Run Code Online (Sandbox Code Playgroud)

这将产生图表。

否则使用此答案total_seconds中概述的方法

更新:

如果数据是每小时的,时间增量以分钟为单位,那么获得您想要的图表的一种方法是这样的:

import datetime as dt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dates = pd.date_range(start=dt.date(2014,10,22), periods=10, freq='H')
df = pd.DataFrame({'start': dates, 'duration': np.random.randint(1, 10, len(dates))}, 
                  columns=['start', 'duration'])
df['duration'] = df.duration.map(lambda x: pd.datetools.timedelta(0, 0, 0, 0, x))
df.ix[1, 1] = pd.datetools.timedelta(0, 0, 0, 0, 30) # To clearly see the effect at 01:00:00
width=[x.minutes/24.0/60.0 for x in df.duration] # mpl will treat x.minutes as days hense /24/60.
plt.bar(left=df.start, width=width, height=[1]*df.start.shape[0])
ax = plt.gca()
_ = plt.setp(ax.get_xticklabels(), rotation=45)
Run Code Online (Sandbox Code Playgroud)

这会生成如下图表:

在此输入图像描述