Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 694
Daniel Lima Avatar asked Dec 05 '25 15:12

Daniel Lima


2 Answers

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)
like image 183
JohanC Avatar answered Dec 07 '25 03:12

JohanC


You can use ax.set_xlim and ax.set_ylim to set the x and y limits of your plot respectively.

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))

# set xlim to be a between certain dates
ax.set_xlim((pd.to_datetime('2019-01-01'), pd.to_datetime('2019-01-31'))

# set ylim to be between certain values
ax.set_ylim((-0.5, 0.5))

series.plot(ax=ax)

like image 20
hkennyv Avatar answered Dec 07 '25 05:12

hkennyv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!