Python - find where the plot crosses the axhline on python plot

2024/10/12 4:29:32

I am doing some analysis on some simple data, and I am trying to plot auto-correlation and partial auto-correlation. Using these plots, I am trying to find the P and Q value to plot in my ARIMA model.

I can see on the graphs, but I am wondering if I can explicitly find, for each graph, where the plot crosses the axhline?

plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle  = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')

So in the above code, can I find, and show, where the lag_pacf plot crosses the axhlines that I have predetermined?

Thanks

Answer

You'll need to calculate the intersections between the line segments of lag_pacf and y's:

from matplotlib import pyplot as plt
import numpy as np
lag_pacf = np.random.randint(-10,10,30)
log_moving_average_difference = [i for i in range(30)]
#plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle  = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()def line_intersection(line1, line2):xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was heredef det(a, b):return a[0] * b[1] - a[1] * b[0]div = det(xdiff, ydiff)if div == 0:return Noned = (det(*line1), det(*line2))x = det(d, xdiff) / divy = det(d, ydiff) / divreturn x, ydef near(a, b, rtol=1e-5, atol=1e-8):return abs(a - b) < (atol + rtol * abs(b))
def crosses(line1, line2):"""Return True if line segment line1 intersects line segment line2 and line1 and line2 are not parallel."""(x1,y1), (x2,y2) = line1(u1,v1), (u2,v2) = line2(a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)e, f = u1-x1, v1-y1denom = float(a*d - b*c)if near(denom, 0):# parallelreturn Falseelse:t = (e*d - b*f)/denoms = (a*f - e*c)/denom# When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the# line segmentsreturn 0<=t<=1 and 0<=s<=1plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle  = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')yys = [0,-1.96/np.sqrt(len(log_moving_average_difference)),1.96/np.sqrt(len(log_moving_average_difference))]
xx, yy = [],[]
xo,yo = [k for k in range(30)],lag_pacf
d = 20
for i in range(1,len(lag_pacf)):for k in yys:p1 = np.array([xo[i-1],yo[i-1]],dtype='float')p2 = np.array([xo[i],yo[i]],dtype='float')k1 = np.array([xo[i-1],k],dtype='float')k2 = np.array([xo[i],k],dtype='float')if crosses((p2,p1),(k1,k2)):seg = line_intersection((p2,p1),(k1,k2))if seg is not None:xx.append(seg[0])yy.append(seg[1]-d)plt.scatter(seg[0],seg[1],c='red')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()

, for this completely randomized example:

Autocorrelation plot with hlines

I obtained this:

Plot with lines interceptions

https://en.xdnf.cn/q/118241.html

Related Q&A

remove tick labels in Python but keep gridlines

I have a Python script which is producing a plot consisting of 3 subplots all in 1 column.In the middle subplot, I currently have gridlines, but I want to remove the x axis tick labels.I have triedax2.…

Signal in PySide not emitted when called by a timer

I need to emit a signal periodically. A timer executes certain function, which emits the signal that I want. For some reason this function is not being emitted. I was able to reproduce the error on min…

pybuilder and pytest: cannot import source code when running tests

so i have a project:<root> |- src|-main|-python|-data_merger|- common|- constans|- controller|- resources|- rest|-tests|-unittest|-integrationtestdata_merger is marked as root (I am using Pycharm…

HTTPS proxy server python

I have a problem with my ssl server (in Python). I set the SSL proxy connection in my browser, and try to connect to my ssl server.This is the server:import BaseHTTPServer, SimpleHTTPServer import sslh…

Python 2.7.6 + unicode_literals - UnicodeDecodeError: ascii codec cant decode byte

Im trying to print the following unicode string but Im receiving a UnicodeDecodeError: ascii codec cant decode byte error. Can you please help form this query so it can print the unicode string properl…

Retrieving data from Quandl with Python

How can I get the latest prices from a Quandl dataset with the Python API (https://www.quandl.com/help/python)? On https://www.quandl.com/help/api, it says "You can use rows=n to get only the fir…

Django: Using same object how to show 2 different results in django template?

Using the same object how to SHOW 2 different results using django template ?In one page there are two divs, it should show different information using the same object.INPUTobject data has follows[{&q…

Override attribute access precedence having a data descriptor

I have a bunch of instances of a MongoEngine model. And the profiler shows that a lot of time is spent in __get__ method of MongoEngine model fields:ncalls tottime percall cumtime percall filename:…

Understanding pythons reverse slice ( [::-1] )

I always thought that omitting arguments in the python slice operation would result into:start = 0 end = len(lst) step = 1That holds true if the step is positive, but as soon as the step is negative, l…

How to print list elements (which are also lists) in separated lines in Python

Ive checked the post and answers on the SO post Printing list elements on separated lines in Python, while I think my problem is a different one.What I want is to transform:lsts = [[1], [1, 1], [1, 2, …