How to get y value from x value in a linear graph?

Given two points in a graph, I want to know what y would be if x was a number of my choosing, for example:

In that graph we have two points (0, 2) and (20, 10), at 15 in x axis; y would be 8.
As a human I know how to do that, all I do is keep looking above 15 until I see the line, then look left of the line until I see what the y value is. But how do I do that with math?

EDIT:

Answer in lua. Note: Function is sensitive to order of points.

local function getY(p1: Vector2, p2: Vector2, x: number)
	local m = (p2.Y - p1.Y) / (p2.X - p1.X)
	return m * x + (p1.Y - (m * p1.X))
end

print(getY(Vector2.new(0, 2), Vector2.new(20, 10), 15)) -- Prints 8 as expected

Given you know 2 points , first get the slope:
image
In your case it’s m = (10-2)/(20-0) = 8/20 = 2/5, using the 2 points.

Use b = y - mx to get b with any of the 2 points:

In your case it’s b = 2 - (2/5*0) (used point 1), so b = 2.

Now your linear function is:
y = mx + b, where b = 2 and m = 2/5.
In your case, y = 2/5 * x + 2

Given any x, you can get y.

EDIT: Had a small mistake at the slope as I was writing it in the bus and did it in mind, sorry!

2 Likes

How are you able to create the graph without the use of y?

1 Like

He probably draws a line based on the way he wishes something scales (level, power, currency etc) and then he wants a way to generate the formula for it.

1 Like

When I switch x with 15 in that y formula, it gives 14 instead of 8. Did I get something wrong?

Editted something while you were typing, review it please, sorry!

Thank you so much! Now it works as it should.

1 Like