在熊猫情节中添加线条

itz*_*tzy 7 python pandas

使用大熊猫,我创建了一个时间序列图,如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我想仅使用2月份的数据在平均值的水平上添加另一条水平线。平均值是ts.loc['2016-02'],但是如何在不包含整个数字的水平上添加一条水平线,而仅针对2月的日期?

piR*_*red 2

您可以使用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)
Run Code Online (Sandbox Code Playgroud)