Python Matplotlib:如何使用带有断条的时间戳?

Python Matplotlib:如何使用带有断条的时间戳?,python,matplotlib,plot,pandas,Python,Matplotlib,Plot,Pandas,我有一个数据框架,时间戳作为索引,列中有数值。 我想使用断开的_条绘制矩形,以突出显示时间序列的某些部分。 如何将时间戳与断开的_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 当我执行上述代码段时,我得到“参数必须

我有一个数据框架,时间戳作为索引,列中有数值。 我想使用断开的_条绘制矩形,以突出显示时间序列的某些部分。 如何将时间戳与断开的_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
当我执行上述代码段时,我得到“参数必须是字符串或数字”错误


提前感谢。

据我所知,熊猫根据索引的频率使用时段值绘制时间序列。这是有意义的,因为matplotlib只将数字理解为轴的值,因此调用
breaked\u barh
失败,因为您传递的是非数字值

要获取时间戳周期的整数值,需要使用
.To\u 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()

你好,罗兰多。谢谢你的回答-在上次熊猫更新之前,它一直对我有效。现在
breaked\u-barh
原因
TypeError:在字符串格式化过程中,并非所有参数都被转换
。您可能知道如何修复它吗?同时,作为一种解决方法:删除序号并使用此处建议的
matplotlib.dates.date2num
,似乎可以解决问题