【问题标题】:Finding intersection of two graphs with different numpy sizes查找具有不同 numpy 大小的两个图的交集
【发布时间】:2021-11-13 00:02:20
【问题描述】:

我想找到两个图的交集。绘制第一张图我用了 674 分,而绘制第二张图只用了 14 分。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv("test1.csv",,skiprows=range(9),names=['A', 'B', 'C','D'])

df2 = pd.read_csv("test2.csv",skiprows=range(1),names=['X','Y'])

x1 = df['A'].tolist()
x1 = np.array(x1)
y1 = df['D'].tolist()
y1 = np.array(y1)
x2 = df2['X'].tolist()
x2 = np.array(x2)
y2 = df2['Y'].tolist()
y2 = np.array(y2)

idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()

fig, ax = plt.subplots()

ax.plot(x1, y1, 'blue')
ax.plot(x2, y2, 'red')

plt.show()

但是,由于 numpy 的大小不同,我从上面的代码中收到此错误。有什么办法可以解决这个问题?

操作数不能与形状 (674,) (14,) 一起广播

【问题讨论】:

  • 你的意思是要找到两条线相交点的坐标吗?如果是这样,那根本就不是直截了当的回答。如果图表不是数学函数,而只是由线连接的数据点,则需要对点之间的值进行插值。
  • 我投票重新打开是因为:Intersection of two graphs in Python, find the x value 没有解决数组长度不同的情况,如当前问题中所述,How do I compute the intersection point of two lines? 仅解决线之间的交叉,而不是曲线。所以这个问题不是他们任何人的重复。

标签: python numpy matplotlib plot scipy


【解决方案1】:

您应该使用scipy.interpolate.interp1d 计算两条曲线的插值,然后您可以使用您使用的方法计算交点的指数。
我假设您有两条曲线,分别具有 x1x2y1y2 坐标,具有不同的长度和 x 轴限制:

x1 = np.linspace(-2, 12, 674)
x2 = np.linspace(0, 8, 14)
y1 = np.sin(x1)
y2 = np.cos(x2) + 1

所以,你必须计算插值函数:

f1 = interp1d(x1, y1, kind = 'linear')
f2 = interp1d(x2, y2, kind = 'linear')

然后,您需要在公共 x 轴上评估新曲线,因此新曲线将具有相同的长度:

xx = np.linspace(max(x1[0], x2[0]), min(x1[-1], x2[-1]), 1000)

y1_interp = f1(xx)
y2_interp = f2(xx)

最后,您可以像之前那样计算插值点的索引:

idx = np.argwhere(np.diff(np.sign(y1_interp - y2_interp))).flatten()

完整代码

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d


x1 = np.linspace(-2, 12, 674)
x2 = np.linspace(0, 8, 14)
y1 = np.sin(x1)
y2 = np.cos(x2) + 1

f1 = interp1d(x1, y1, kind = 'linear')
f2 = interp1d(x2, y2, kind = 'linear')

xx = np.linspace(max(x1[0], x2[0]), min(x1[-1], x2[-1]), 1000)

y1_interp = f1(xx)
y2_interp = f2(xx)

idx = np.argwhere(np.diff(np.sign(y1_interp - y2_interp))).flatten()


fig, ax = plt.subplots()

ax.plot(x1, y1, 'blue', label = 'y1')
ax.plot(x2, y2, 'red', label = 'y2')
for index in idx:
    ax.plot(xx[index], y1_interp[index], marker = 'o', markerfacecolor = 'black', markeredgecolor = 'black')

plt.show()

情节

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2018-05-12
    • 2013-01-28
    • 2012-11-09
    • 2023-04-09
    • 2017-07-15
    • 2022-11-03
    相关资源
    最近更新 更多