pythonpandasplot

Set margins of a time series plotted with pandas


I have the following code for generating a time series plot

import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
series = pd.Series([np.sin(ii*np.pi) for ii in range(30)],
                   index=pd.date_range(start='2019-01-01', end='2019-12-31',
                                       periods=30))
series.plot(ax=ax)

enter image description here

I want to set an automatic limit for x and y, I tried using ax.margins() but it does not seem to work:

ax.margins(y=0.1, x=0.05)
# even with
# ax.margins(y=0.1, x=5)

enter image description here

What I am looking for is an automatic method like padding=0.1 (10% of whitespace around the graph)


Solution

  • Pandas and matplotlib seem to be confused rather often while collaborating when axes have dates. For some reason in this case ax.margins doesn't work as expected with the x-axis.

    Here is a workaround which does seem to do the job, explicitely moving the xlims:

    xmargins = 0.05
    ymargins = 0.1
    ax.margins(y=ymargins)
    x0, x1 = plt.xlim()
    plt.xlim(x0-xmargins*(x1-x0), x1+xmargins*(x1-x0))
    

    Alternatively, you could work directly with matplotlib's plot, which does work as expected applying the margins to the date axis.

    ax.plot(series.index, series)
    ax.margins(y=0.1, x=0.05)
    

    PS: This post talks about setting use_sticky_edges to False and calling autoscale_view after setting the margins, but also that doesn't seem to work here.

    ax.use_sticky_edges = False
    ax.autoscale_view(scaley=True, scalex=True)