在绘制以timedeltas为索引的pandas系列时格式化x轴

问题描述 投票:0回答:1

我想用timedeltas作为索引绘制一个pandas系列,并自定义x-tick格式。最小的example将是:

import pandas as pd
import matplotlib.pyplot as plt
times = ['Wed Feb 20 08:28:04 PST 2019', 'Wed Feb 20 09:29:04 PST 2019', 'Wed Feb 20 10:30:04 PST 2019']
timestamps = [pd.Timestamp(t) for t in times]
timedeltas = [t - timestamps[0] for t in timestamps]
timedeltas
ts = pd.Series([1, 2, 5], index=timedeltas)
ts.plot()
plt.savefig("/tmp/plot.png")`

Which produces the following
[output][1].

我想将timedeltas格式化为[小时]:[分钟]。

添加

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))

导致以下错误:

ValueError: Cannot convert -1000000000000 to a date.  This often happens if non-datetime values are passed to an axis that expects datetime objects.
python pandas matplotlib timedelta
1个回答
0
投票

这里的问题是我们无法格式化timedeltas。

@Shawn Chin here有一个很好的解决方案

我已经编辑了他的答案较轻,以便在适用的时间和分钟中添加前导零,仅仅因为我觉得它看起来更好。虽然它也会将天数限制为2位数,但是根据您的问题,我假设您只想显示小时和分钟。

Shawn略微编辑的功能:

def strfdelta(tdelta, fmt):
    d = {"days": tdelta.days}
    d["hours"], rem = divmod(tdelta.seconds, 3600)
    d["minutes"], d["seconds"] = divmod(rem, 60)
    for key in d:
        d[key] = "{:02d}".format(d[key])
    return fmt.format(**d)

在代码中添加一行以调用此函数我希望得到您之后的输出:

import pandas as pd
import matplotlib.pyplot as plt
times = ['Wed Feb 20 08:28:04 PST 2019', 'Wed Feb 20 09:29:04 PST 2019', 'Wed Feb 20 10:30:04 PST 2019']
timestamps = [pd.Timestamp(t) for t in times]
timedeltas = [t - timestamps[0] for t in timestamps]
timedeltas = [strfdelta(t, '{hours}:{minutes}') for t in timedeltas]
ts = pd.Series([1, 2, 5], index=timedeltas)
ts.plot()

Line Chart Output

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.