Miguel Santos
Miguel Santos

Reputation: 39

Find graphs intersection python

Does anyone have any idea of how I can find the intersection of these two graphs? (image below)

energ_ac, price_compvend and energ_ac1, price_compven1 are set of x,y values.

Please note the following code which gets the values from a database and then plots the two graphs:

I can only get the intersection manually, and I want to get it automatically


import matplotlib.pyplot as plt
import pyodbc
import pandas as pd
import numpy as np
import string as str
import sys

np.set_printoptions(suppress=True)
np.set_printoptions(threshold=sys.maxsize)

conn = pyodbc.connect(Trusted_Connection='yes', driver='{SQL Server}', server='srv03',
                                  database='mercadoOMIE_curvas')  # Ligação à BD no sqlserver


SQL_Query = pd.read_sql_query("""SELECT * FROM curva_pbc_uof_2020_1_12 WHERE ("4" = 'C' AND "0" = '1' AND "7" = 'O')""", conn)

df = pd.DataFrame(SQL_Query, columns=['0','1','2','3','4','5','6','7','8'])


df['5'] = df['5'].str.replace('.','', regex = True)

df['6'] = df['6'].str.replace('.','', regex = True)


df['5'] = pd.to_numeric(df['5'].str.replace(',','.'), errors='coerce')

df['6'] = pd.to_numeric(df['6'].str.replace(',','.'), errors='coerce')


energ_ac = np.zeros(len(df['5']))

energ_ac[0] = df['5'][0]

for x in range (1, len(df['5'])):
    energ_ac[x] = energ_ac[x-1]+df['5'][x]

price_compvend = df['6'].to_numpy()

plt.plot(energ_ac,price_compvend)



SQL_Query1 = pd.read_sql_query("""SELECT * FROM curva_pbc_uof_2020_1_12 WHERE ("4" = 'V' AND "0" = '1' AND "7" = 'O')""", conn)
df1 = pd.DataFrame(SQL_Query1, columns=['0','1','2','3','4','5','6','7','8'])

#with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
    #print(df1)

df1['5'] = df1['5'].str.replace('.','', regex = True)

df1['6'] = df1['6'].str.replace('.','', regex = True)


df1['5'] = pd.to_numeric(df1['5'].str.replace(',','.'), errors='coerce')

df1['6'] = pd.to_numeric(df1['6'].str.replace(',','.'), errors='coerce')

energ_ac1 = np.zeros(len(df1['5']))

energ_ac1[0] = df1['5'][0]

for x in range (1, len(df1['5'])):
    energ_ac1[x] = energ_ac1[x-1]+df1['5'][x]

price_compvend1 = df1['6'].to_numpy()

plt.plot(energ_ac1,price_compvend1)




plt.show()

enter image description here

Upvotes: 2

Views: 315

Answers (3)

Miguel Santos
Miguel Santos

Reputation: 39

The solution is this link: np.array intersection // AttributeError: 'module' object has no attribute 'PiecewisePolynomial'

import scipy.interpolate as interpolate
import scipy.optimize as optimize
import numpy as np

x1 = np.array([1.4,2.1,3,5.9,8,9,23])
y1 = np.array([2.3,3.1,1,3.9,8,9,11])
x2 = np.array([1,2,3,4,6,8,9])
y2 = np.array([4,12,7,1,6.3,8.5,12])    

# linear interpolators
opts = {'fill_value': 'extrapolate'}
f1 = interpolate.interp1d(x1,y1,**opts)
f2 = interpolate.interp1d(x2,y2,**opts)

# possible range for an intersection
xmin = np.min((x1,x2))
xmax = np.max((x1,x2))

# number of intersections
xuniq = np.unique((x1,x2))
xvals = xuniq[(xmin<=xuniq) & (xuniq<=xmax)]
# note that it's bad practice to compare floats exactly
# but worst case here is a bit of redundance, no harm

# for each combined interval there can be at most 1 intersection,
# so looping over xvals should hopefully be enough
# one can always err on the safe side and loop over a `np.linspace`

intersects = []
for xval in xvals:
    x0, = optimize.fsolve(lambda x: f1(x)-f2(x), xval)
    if (xmin<=x0<=xmax
        and np.isclose(f1(x0),f2(x0))
        and not any(np.isclose(x0,intersects))):
        intersects.append(x0)

print(intersects)
print(f1(intersects))
print(f2(intersects))

Upvotes: 1

nushen
nushen

Reputation: 61

You could use set.intersection() method to get intersection points of the graphs.

graph_points1 = set(zip(energ_ac,price_compvend))
graph_points2 = set(zip(energ_ac1,price_compvend1))
intersection_points = graph_points1.intersection(graph_points2)

Upvotes: 0

Sadra Sabouri
Sadra Sabouri

Reputation: 309

Use bellow script:

diff_vector = abs(price_compvend - price_compvend1)
min_index = np.where(diff_vector == np.min(diff_vector))
print('Intersection point is ({},{})'.format(energ_ac[min_index],
                                      price_compvend[min_index]))

Upvotes: 0

Related Questions