我有一个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
当我执行上面的代码片段时,我得到'参数必须是字符串或数字'错误.
提前致谢.
据我所知,大熊猫根据索引的频率使用周期值绘制时间序列.这是有道理的,因为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()