Move the points in the graph linearly when a point is moved up/down and edge values should be fixed in Javascript

32 Views Asked by At

I have a chart in which a line is plotted randomly and when we move a point up/down the other points should update the values such that a new linear plot should appear.

Example image about the expected output

In the image the blue line is the original and when a point is moved up as you can see the red line. Now how to calculate the new points such that it forms the linear green line.

I think it should be something related to linear equation like calculating the slope and then adding it to the other values but I dont think its working. Maybe I'm doing something wrong

1

There are 1 best solutions below

0
KompjoeFriek On

This can be done by splitting the graph in 2 straight lines, and interpolate the intermediate values.

A basic example of interpolation

Lets say you have a list of 4 items which form a straight line but only know the first and last value:

[ 5, ??, ??, 14]

To get those missing values, we can calculate a step size by which each value changes compared to the value before it:

Get the difference between the last and the first item 14 - 5 = 9, and divide it by the number of steps to take 4 - 1 = 3. This gives us a step size of 9 / 3 = 3.

Apply the step size to your data:

[ 5+(3*0), 5+(3*1), 5+(3*2), 5+(3*3) ] or [ 5, 8, 11, 14 ]

Back to your problem

Because you will have 3 fixed points, this gives you 2 lines. The first line is from the first value to the value you change. The second line is from the changed value to the last value.

Here is an example of how to do just that:

function moveDatapoint(data, changedIndex, changedValue) {
  if (data != null && changedIndex > 0 && changedIndex < data.length - 1) {
    // first line
    let diff = changedValue - data[0] // the change from start point to the changed point
    let stepsize = diff / changedIndex
    for (let i = 1; i < changedIndex; i++) {
      data[i] = data[0] + stepsize * i
    }

    // changed point
    data[changedIndex] = changedValue

    // second line
    diff = data[data.length - 1] - changedValue // the change from changed point to the last point
    stepsize = diff / (data.length - changedIndex)
    for (let i = changedIndex + 1; i < data.length - 1; i++) {
      data[i] = changedValue + stepsize * (i - changedIndex + 1)
    }
  }
}

//             Jan  Feb  Mar  Apr  May Jun Jul Aug Sep Oct Nov Dec
let myData = [600, 580, 470, 395, 300, 90, 90, 90, 89, 88, 86, 83]
console.log("Original data:")
console.log(myData)

moveDatapoint(myData, 7, 600)
console.log("After moving datapoint:")
console.log(myData)