Swapnil
Swapnil

Reputation: 401

How to find y coordinate on line B with respective x coordinate of line A

I have two line on graph using matplotlib in python

Line A

A_X = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
A_Y = [33300.0, 32887.6, 33046.4, 33140.9, 32967.8, 32960.0, 33128.95, 33376.95, 33300.0, 33080.0]

Line B which has first and last point from Line A to draw straight line between those points.

B_X = [11, 20]
B_Y = [33300.0, 33080.0]

So now i want to find all y reference coordinates for B_X 12 to B_X 19 x coordinate.
Basically from the below image I want to find coordinates for red points. Thank you in advance for huge help.

Line A & B

Upvotes: 1

Views: 736

Answers (2)

Zephyr
Zephyr

Reputation: 12496

You should create an interpolation function with interp1d:

line = interp1d(B_X, B_Y)

Then choose the X points you want to use for the interpolation and call the interpolation function on them:

B_X_points = np.arange(B_X[0], B_X[-1] + 1, 1)
B_Y_points = line(B_X_points)

Complete Code

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

A_X = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
A_Y = [33300.0, 32887.6, 33046.4, 33140.9, 32967.8, 32960.0, 33128.95, 33376.95, 33300.0, 33080.0]

B_X = [11, 20]
B_Y = [33300.0, 33080.0]

line = interp1d(B_X, B_Y)
B_X_points = np.arange(B_X[0], B_X[-1] + 1, 1)
B_Y_points = line(B_X_points)

fig, ax = plt.subplots()

ax.plot(A_X, A_Y)
ax.plot(B_X_points, B_Y_points, marker = 's', markerfacecolor = 'r')

plt.show()

enter image description here

Upvotes: 2

mbcalli
mbcalli

Reputation: 51

Use linear interpolation with the scipy module:

from scipy.interpolate import interp1d

f = interp1d(B_X, B_Y)

To get the y values for the red points use

f(A_X)

Coordinates for the red points will be (A_X, f(A_X))

Upvotes: 2

Related Questions