据我了解,pandas 根据索引的频率使用周期值来绘制时间序列。这是有道理的,因为 matplotlib 仅将数字理解为轴的值,因此您的调用broken_barh
失败是因为您传递的是非数字值。
要获取时间戳周期的整数值,您需要使用.to_period()
. See:
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()