views:

27

answers:

2

I'm making a simple JavaScript graphing library using the canvas element. I really suck at math so I'm stuck with a simple issue.

If I have a number - for example 30000, and I want to plot it relatively to graph's height which is 400. How do I calculate the y value for that?

+2  A: 

You would want to figure out your max for the graph. Say, in this case 50000. Then, take your height and divide it by the max (so 400/50000) to get a ratio multiplier. Any number you want to plot you multiply by that ratio and that should give you a number that fits on your space. Is that what you're asking for?

Dante617
There is no limit in terms of data.
Nick Brooks
But you have to figure out how high your chart is, right? It's going to be a lot of scrolling down if your top number in the chart is infinity. :) For that, you can figure out your max data point and then just give the chart a bit of a buffer. So, if the highest Y you have to chart at the moment is 30000, make your top point 40000.
Dante617
A: 

For that you need to first find out the maximum and minimum values that you need to plot. For example, in this list of (x,y) coordinates: [(1,3),(2,10),(3,0),(4,-10)], the max value is 10 and the min value is -10. This gives you a span of (max-min = 10-(-10) = ) 20.

Notice that you can now translate the set of y values into a number in the range [0,max-min] (i.e. [0,20] in this case). Here, a value of 0 will get plotted as a 0 in the graph and a value of 20 will get plotted as 400. Also, a value of 20/2 will be plotted as 400/2. Thus, a value of 20/x is plotted as 400/x. This means that any value can now be plotted as 400*value/20.

So, to translate a given value n to its corresponding y value on the graph, simply convert n to (n-min)*400/(max-min).

MAK