Search code examples
pythonmatplotlibsubplot

Changing subplot axes range when calling plot_pacf as one of the suplots


I am having trouble setting different x-axis ranges for some subplots I am making. As far as I can gather, this could be because the plot_pacf() function was called instead of using axes2.plot()

The code is:

# PACF plot of 1st differenced series
plt.rcParams.update({'figure.figsize':(9,3), 'figure.dpi':120})

# I do not know why the data is defaulting to starting from 1970..but this is my attempt to fix it
x_axis_min = datetime.datetime(2013, 1, 1)
x_axis_max = datetime.datetime(2015, 6, 30)
x_axis_min_pacf = datetime.datetime(1969, 12, 31)
x_axis_max_pacf = datetime.datetime(1970, 2, 1)

fig, (axes1, axes2) = plt.subplots(1, 2, sharex=True)

# differencing plot
axes1.plot(store1_train.Sales.diff())
axes1.set_title('1st Differencing')
axes1.set_xlim(x_axis_min, x_axis_max)
axes1.tick_params(axis='x', labelrotation=90)

# pacf plot
plot_pacf(store1_train.Sales.diff().dropna(), ax=axes2)
axes2.set_xlim(x_axis_min_pacf, x_axis_max_pacf)
axes2.set_ylim((0,1.1))
axes2.tick_params(axis='x', labelrotation=90)

plt.show()

However the output doesn't set a specific x-axis range for each subplot. Instead it just takes x_axis_min_pacf and x_axis_max_pacf as the range for both subplots

enter image description here

(note: I know the x-axis date ranges don't make sense/arent' comparable between axes1 and axes2. That is a separate issue that has led to this question's problem)


Solution

  • First of all, it’s the same issue with sharex=True as in your other post here and that is why it takes x_axis_min_pacf and ‘x_axis_max_pacf’ for both plots:

    Differencing and Autocorrelation Function plots x-axis extends far beyond dataset range

    Secondly, it does not really make sense to set the ticks on the x axis to dates, because the pacf correlation values are not really date related. The correlation works for every observation in the dataset and does not really have anything to do with the date.

    Therefore, I would recommend to remove the line axes2.set_xlim(x_axis_min_pacf, x_axis_max_pacf) and use numeric values (representing the number of lags) instead. You can however draw some lines in the pacf plot to increase legibility. Add something like this before plot_pacf(…):

    number_of_lags=30
    steps_with_lines=7
    for x in range(0, number_of_lags+1, steps_with_lines):
    
        plt.axvline(x=x, ymin=0, ymax=1, color="lightblue", linestyle="--")