2016-05-10 81 views
3

使用熊猫我创建了一个时间序列的情节是这样的:行添加到大熊猫绘制

import numpy as np 
import pandas as pd 

rng = pd.date_range('2016-01-01', periods=60, freq='D') 
ts = pd.Series(np.random.randn(len(rng)), index=rng) 

ax = ts.plot() 
ax.axhline(y=ts.mean(), xmin=-1, xmax=1, color='r', linestyle='--', lw=2) 

enter image description here

我想只使用数据的平均水平增加另一个水平线从二月开始。平均值只是ts.loc['2016-02'],但是如何在该级别添加横跨整个数字的水平线,但仅限于2月份的日期?

回答

1

您可以使用xminxmax来控制图表开始和结束的位置。但这是图表的百分比。

import numpy as np 
import pandas as pd 

np.random.seed([3, 1415]) 
rng = pd.date_range('2016-01-01', periods=60, freq='D') 
ts = pd.Series(np.random.randn(len(rng)), index=rng) 
ts_feb = ts['2016-02'] 

# used to figure out where to start and stop 
ts_len = float(len(ts)) 
ts_len_feb = float(len(ts_feb)) 
ratio = ts_len_feb/ts_len 

ax = ts.plot() 
ax.axhline(y=ts.mean() * 5, xmin=0, xmax=1, color='r', linestyle='--', lw=2) 
ax.axhline(y=ts_feb.mean() * 5, xmin=(1. - ratio), xmax=1, color='g', linestyle=':', lw=2) 
1

或者您可以创建一个新的时间序列,其值是平均值,而索引仅涵盖2月份。

ts_feb_mean = ts['2016-02'] * 0 + ts['2016-02'].mean() 

总之,它看起来像:

import numpy as np 
import pandas as pd 

rng = pd.date_range('2016-01-01', periods=60, freq='D') 
ts = pd.Series(np.random.randn(len(rng)), index=rng) 

# Feb mean 
ts_fm = ts['2016-02'] * 0 + ts['2016-02'].mean() 
ts_fm = ts_fm.reindex_like(ts) 

# Total mean 
ts_mn = ts * 0 + ts.mean() 

# better control over ax 
fig, ax = plt.subplots(1, 1) 
ts.plot(ax=ax) 
ts_mn.plot(ax=ax) 
ts_fm.plot(ax=ax)