Matplotlib:如何将时间戳记与broken_barh一起使用? [英] Matplotlib: How to use timestamps with broken_barh?

查看:287
本文介绍了Matplotlib:如何将时间戳记与broken_barh一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,其中时间戳作为索引,列中包含数值. 我想使用broken_bar绘制矩形以突出显示时间序列的某些部分.

I have a pandas dataframe with timestamps as index and numeric values in the columns. I want to use broken_bar to draw rectangles to highlight some portions of the timeseries. How to use timestamps with 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

执行上面的代码片段时,出现参数必须是字符串或数字"错误.

When I execute the above snippet, I get 'argument must be a string or a number' error.

谢谢.

推荐答案

据我了解,熊猫通过根据索引频率使用周期值来绘制时间序列.这是有道理的,因为matplotlib仅将数字理解为轴的值,因此您调用broken_barh失败,因为您传递的是非数字值.

As far I understand, pandas plot timeseries by using period values according to the frequency of your index. This makes sense because matplotlib only understands number as values for the axis and thus your call to broken_barh fails because your are passing a non-number value.

要获取时间戳记周期的整数值,您需要使用.to_period().参见:

To get the integer value of a period of a timestamp you need to use .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

然后,根据时间戳记间隔(天,周,月等),您需要弄清楚要用于折线的宽度是多少.

Then, depending on your timestamps interval (days, weeks, months, etc) you need to figure out what's the width you want to use for the broken bar.

在下面的示例中,频率为1天,一周的条形宽度为7个单位.

In the example below, the frequency is 1 day and the width of the bar for one week is 7 units.

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()

这篇关于Matplotlib:如何将时间戳记与broken_barh一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆