Add line to pandas plot Add line to pandas plot python python

Add line to pandas plot


Or you can create a new time series whose values are the mean and index only spans February.

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

All together it looks like:

import numpy as npimport pandas as pdrng = pd.date_range('2016-01-01', periods=60, freq='D')ts = pd.Series(np.random.randn(len(rng)), index=rng)# Feb meants_fm = ts['2016-02'] * 0 + ts['2016-02'].mean()ts_fm = ts_fm.reindex_like(ts)# Total meants_mn = ts * 0 + ts.mean()# better control over axfig, ax = plt.subplots(1, 1)ts.plot(ax=ax)ts_mn.plot(ax=ax)ts_fm.plot(ax=ax)


You can use xmin and xmax to control where in the chart the line starts and ends. But this is in percent of the chart.

import numpy as npimport pandas as pdnp.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 stopts_len = float(len(ts))ts_len_feb = float(len(ts_feb))ratio = ts_len_feb / ts_lenax = 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)