以timedelta为条形宽度的条形图 [英] Bar plot with timedelta as bar width

查看:76
本文介绍了以timedelta为条形宽度的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据帧,其中一列包含时间戳(start),另一列包含时间戳(duration)来指示持续时间.

I have a pandas dataframe with a column containing timestamps (start) and another column containing timedeltas (duration) to indicate duration.

我正在尝试绘制条形图,以显示这些持续时间,并在时间戳记的左侧显示这些持续时间.无论如何我都没有在线找到它.有什么办法可以做到这一点?

I'm trying to plot a bar chart showing these durations with their left edge at the timestamps. I haven't found anyway online of doing it. Is there any way to achieve this?

到目前为止,这是我所拥有的,这是行不通的:

So far, this is what I have, which doesn't work:

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

修改: 我更新了宽度,如下所示,但这也不能解决此问题:

I have updated the width as follows but that also doesn't solve this problem:

width = [x.total_seconds()/(60*1200) for x in df['duration']]

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

I'm interested in knowing whether datetime.timedelta objects can be used in width, since datetime objects can be used as x-axis. And if not, what alternatives are there?

编辑#2:

这可能不是我所提问题的确切答案,但它解决了我的初衷.对于感兴趣的人,这是我最终采用的方法(为此目的,我使用startduration制作了end)

This may not be the exact answer to my question, but it solved the purpose I had in mind. For whoever interested, this is the approach I took finally (I used start and duration to make end for this purpose):

    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)

推荐答案

如果您的df.duration[0]类型为pandas.tslib.Timedelta,而您的timestamps相距几天,则可以使用:

If type of your df.duration[0] is pandas.tslib.Timedelta and your timestamps are days apart you could use:

width = [x.days for x in df.duration]

这将产生图表.

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

Otherwise use total_seconds method as outlined in this answer

更新:

如果数据以小时为单位,以小时为单位,则以分钟为单位,那么获取所需图表的一种方法是这样的:

If the data is hourly with timedeltas in minutes then one way to have the chart you want is like this:

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)

这将产生如下图表:

这篇关于以timedelta为条形宽度的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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