在绘制以时间增量为索引的熊猫系列时设置x轴的格式

时间:2019-02-21 16:39:07

标签: python pandas matplotlib timedelta

我想绘制一个以timedeltas为索引的熊猫系列,并自定义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].

我想将时间间隔格式设置为[小时]:[分钟]。

添加

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.

1 个答案:

答案 0 :(得分:0)

这里的问题是我们无法格式化时间增量。

@Shawn Chin here

有一个很好的解决方案

我已经稍微修改了他的答案,以便在适用的小时和分钟数中添加前导零,这仅仅是因为我认为它看起来更好。尽管也将天数限制为两位数,但是从您的问题来看,我假设您只想显示小时和分钟。

肖恩的功能略有修改:

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

希望这会有所帮助!