【问题标题】:Find graphs intersection python查找图形交集python
【发布时间】:2021-02-22 12:23:18
【问题描述】:

有人知道如何找到这两个图的交集吗? (下图)

energ_acprice_compvendenerg_ac1price_compven1 是一组 xy 值。

请注意以下代码,它从数据库中获取值,然后绘制两个图表:

只能手动获取路口,想自动获取


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

【问题讨论】:

标签: python matplotlib


【解决方案1】:

解决方法是这个链接: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))

【讨论】:

    【解决方案2】:

    使用下面的脚本:

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

    【讨论】:

    • 我收到此错误:回溯(最近一次调用最后一次):文件“C:/Users/miguel.santos/PycharmProjects/mercadoOMIE/venv/OMIE_analise.py”,第 88 行,在 diff_vector = abs(price_compvend - price_compvend1) ValueError: 操作数不能与形状一起广播 (521,) (​​1113,)
    • 好的,所以把大的截断让它变小,你可以使用:price_compvend1 = price_compvend1[0:price_compvend.size] price_compvend 是较小的。
    • 我得到这个结果:交叉点是([29154.8 29165.7 34535.1 39572.8 39613.8 39613.8 39613.9 39613.9 39613.9 39613.9 39613.9 39613.9 39613.9 39613.9 39613.9 39613.9 39664.],[0。 0. 0. 0. 0. 0. 0.])
    【解决方案3】:

    您可以使用set.intersection() 方法获取图形的交点。

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

    【讨论】:

    • 不可能。交点可能是未包含在值集中的点
    猜你喜欢
    • 2016-12-27
    • 2021-12-06
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多