使用大熊猫,我创建了一个时间序列图,如下所示:
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月的日期?
您可以使用xmin和xmax来控制图表中线条的开始和结束位置。但这是图表的百分比。
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)
| 归档时间: |
|
| 查看次数: |
7483 次 |
| 最近记录: |