Matplotlib: 如何在broken_barh中使用时间戳?

2 投票
1 回答
6167 浏览
提问于 2025-04-18 11:08

我有一个 pandas 数据框,它的索引是时间戳,列里是一些数字值。
我想用 broken_bar 来画矩形,以突出显示时间序列中的某些部分。
我该如何在 broken_barh 中使用时间戳呢?

df.plot(ax = ax)
ax.broken_barh([(startTs, pd.offsets.Week())], (10,50), facecolors = colors, alpha = 0.25)
# Where type(startTs) is pandas.tslib.Timestamp

当我执行上面的代码时,出现了“参数必须是字符串或数字”的错误。

提前谢谢你。

1 个回答

10

根据我的理解,pandas在绘制时间序列图时,会根据你索引的频率使用周期值。这是有道理的,因为matplotlib只理解数字作为坐标轴的值,所以你调用broken_barh时出错,是因为你传入了一个非数字的值。

要获取时间戳的周期的整数值,你需要使用.to_period()。看看这个:

In [110]: pd.to_datetime('2014-04-02').to_period('D').ordinal
Out[110]: 16162

In [111]: pd.to_datetime('2014-04-02').to_period('W').ordinal
Out[111]: 2310

然后,根据你的时间戳的间隔(比如天、周、月等),你需要确定你想要为断裂条形图使用的宽度。

在下面的例子中,频率是1天,而一周的条形宽度是7个单位。

import numpy as np
import matplotlib.pylab as plt
import pandas as pd

idx = pd.date_range('2013-04-01', '2013-05-18', freq='D')
df = pd.DataFrame({'values': np.random.randn(len(idx))}, index=idx)
ax = df.plot()

start_period = idx[0].to_period('D').ordinal
bar1 = [(start_period, 7), (start_period + 10, 5), (start_period + 25, 4)]
bar2 = [(start_period, 1), (start_period + 22, 3), (start_period + 40, 2)]
ax.broken_barh(bar1, [2, .2], facecolor='red')
ax.broken_barh(bar2, [-2, .2], facecolor='green')
plt.show()

带时间戳的断裂条形图

撰写回答