【问题标题】:plot pandas period_range with matplotlib - set freq of axis用 matplotlib 绘制 pandas period_range - 设置轴的频率
【发布时间】:2016-06-14 21:03:31
【问题描述】:

我得到了一个带有可变长度的时间跨度值的 pandas DataFrame。我想用时间跨度的长度为每个时间跨度的值绘制一条水平线。因此,我通过

将时间跨度转换为 PeriodIndex
ax0=fig.add_axes([.16,.2,0.8,.7])
ax0.plot_date(data['periodIndex'], data['value'])

产生:

TypeError: Axis must have `freq` set to convert to Periods

所以我的问题是如何设置我的 xaxis 的频率

非常感谢您的帮助

阿克塞尔

更新

这是我要绘制的 pandas dataFrame 的一部分

     start        stop          A           B          C
ID                                                                    
1    2015-08-17   2015-08-25    -5.684246  -34.759047  10.714920   
2    2015-08-25   2015-09-02   -10.850721  -78.443556   8.362215   
3    2015-09-02   2015-09-15    -7.139351  -47.814199   9.300612   
4    2015-09-15   2015-09-21    -7.822367  -56.895241   5.683696   
5    2015-09-21   2015-09-29    -6.491543  -42.947744   8.984596   
6    2015-09-29   2015-10-05    -9.897980  -67.985256  11.198583  

我解决了这个问题,现在看起来像 this 通过以下代码

firstDate=df.ix[df.index[0]]['start']

fig=plt.figure(figsize=(9*1.5,6*1.5))
ax0=fig.add_axes([.15,.2,0.75,.7])

ax0.set_xticks(df['start_abs'])
ax0.set_xticklabels([i.date() for i in df['start']], rotation='vertical')

B=ax0.twinx()
B.set_ylim(-200,0)

for _index, _series in df.iterrows():
    start=_series['start']
    stop=_series['stop']   
    df.ix[_index, 'start_abs']=(start-firstDate).days
    df.ix[_index, 'width_abs']=(stop-start).days
    df.ix[_index, 'stop_abs']=(stop-firstDate).days

    line_A=ax0.hlines(y=df.ix[_index,'A'], xmin=df.ix[_index, 'start_abs'], xmax=df.ix[_index, 'stop_abs'], colors='r')
    line_A.set_linewidths(3)
    text_A=ax0.text(df.ix[_index, 'start_abs'], df.ix[_index,'A'], '{a:4.2f}'.format(a=df.ix[_index,'A']), fontsize=8, color='r')

    line_B=B.hlines(y=df.ix[_index,'B'], xmin=df.ix[_index,'start_abs'], xmax=df.ix[_index,'stop_abs'], colors='k')
    line_B.set_linewidths(3)
    text_B=B.text(df.ix[_index,'start_abs'], df.ix[_index,'B'], '{a:4.2f}'.format(a=df.ix[_index,'B']), fontsize=8, color='k')

plt.show()

【问题讨论】:

  • 请提供data
  • 很抱歉,如果您需要帮助,您必须重新表述您的问题并提供包含一些数据行的示例。提供的示例不清楚,因为您谈论的是周期索引转换,并且代码未显示此转换,例如df['date'].dt.to_period('H').

标签: python pandas matplotlib


【解决方案1】:

我构建了数据来证明我认为是您的问题。

如果您仅使用索引特定范围的数据填充数据框,然后绘制它,它只会在该数据不为空时生成一条线。

import pandas as pd
import numpy as np

ts = pd.date_range(end='2016-03-31', periods=250, freq='D')

np.random.seed([3,1415])
ranges = pd.DataFrame((np.random.choice(xrange(100), (2, 10)) +
                       np.array([[0], [150]])),
                      columns=list('ABCDEFGHIJ'))

df = pd.DataFrame(index=ts)
count = 1
for i, c in ranges.iteritems():
    s, e = c
    df.loc[ts[s]:ts[e], i] = count
    count += 1

df.plot()

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2020-07-31
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2020-10-01
    • 1970-01-01
    相关资源
    最近更新 更多