33
fig = plt.figure()
ax = fig.gca()
ts.plot(ax=ax)

I know I can set xlim inside pandas plotting routine: ts.plot(xlim = ...), but how to change it after pandas plotting is done?

ax.set_xlim(( t0.toordinal(), t1.toordinal() )

works sometimes, but if pandas is formatting the x-axis as months from epoch, not days, this will fail.

Is there anyway to know how pandas has converted the dates to x-axis and then convert my xlim in the same way?

cottontail
  • 10,268
  • 18
  • 50
  • 51
jf328
  • 6,841
  • 10
  • 58
  • 82

2 Answers2

46

It works for me (with pandas 0.16.2) if I set the x-axis limits using pd.Timestamp values.

Example:

import pandas as pd

# Create a random time series with values over 100 days
# starting from 1st March.
N = 100
dates = pd.date_range(start='2015-03-01', periods=N, freq='D')
ts = pd.DataFrame({'date': dates,
                   'values': np.random.randn(N)}).set_index('date')

# Create the plot and adjust x/y limits. The new x-axis
# ranges from mid-February till 1st July.
ax = ts.plot()
ax.set_xlim(pd.Timestamp('2015-02-15'), pd.Timestamp('2015-07-01'))
ax.set_ylim(-5, 5)

Result:

Plot of time series with x-axis limits manually adjusted.

Note that if you plot multiple time series in the same figure then make sure to set xlim/ylim after the last ts.plot() command, otherwise pandas will automatically reset the limits to match the contents.

cilix
  • 1,262
  • 1
  • 14
  • 14
0

For a more "dynamic" setting of axis limits, you can subtract/add Timedelta from a datetime. For example, to have a 1-day padding on either side of x-axis limits, you can use the following.

dates = pd.date_range(start='2015-03-01', periods=100, freq='h')
ts = pd.DataFrame({'date': dates, 'values': np.random.randn(len(dates))})

# plot the time-series
ax = ts.plot(x='date', y='values', legend=False)
# set x-axis limits with the extra day padding
ax.set(xlim=(ts['date'].min() - pd.Timedelta('1d'), ts['date'].max() + pd.Timedelta('1d')));

You can also set the axis limits inside the plot() call.

ts.plot(x='date', y='values', 
        xlim=(ts['date'].min() - pd.Timedelta('1d'), ts['date'].max() + pd.Timedelta('1d')));

result image

cottontail
  • 10,268
  • 18
  • 50
  • 51