【问题标题】:Format x-axis when plotting pandas series with timedeltas as indices绘制以 timedeltas 作为索引的 pandas 系列时格式化 x 轴
【发布时间】:2019-02-21 16:39:07
【问题描述】:

我想绘制一个以 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].

我想将时间增量格式化为 [小时]:[分钟]。

添加

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.

【问题讨论】:

  • matplotlib.dates 严格要求单位为天。熊猫情节可能使用完全不同的单位。因此,matplotlib 格式化程序和定位器一般不适用于熊猫图。在许多情况下,您可以使用x_compat=True,但不能用于时间增量。如果您需要使用 matplotlib 格式化程序,请先将时差转换为天数。

标签: python pandas matplotlib timedelta


【解决方案1】:

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

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

我稍微编辑了他的答案,以便在适用的小时和分钟中添加前导零,仅仅是因为我认为它看起来更好。虽然它也会将天数限制为 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()

希望这会有所帮助!

【讨论】:

  • 非常感谢您的回答。但是对我来说,x 轴上没有标签。我将 Python 3.6.7 与 pandas 0.22.0 和 matplotlib 3.0.0 一起使用,以防万一。
  • @spurdo 很抱歉听到这个消息。你能告诉我 ts 对你来说是什么样的吗?
  • @spurdo 这些值是否出现在您的熊猫系列中,即 ts 变量中?
猜你喜欢
  • 2018-12-08
  • 2018-06-17
  • 2015-02-04
  • 2017-03-24
  • 2017-04-24
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多