1

For example I have chart with 2 points - 0,0 and 10,10 and chart type is FastLine. I want to know what Y value will be in chart in choosen X value.

For example when X is 5 I want to know that Y is 5.

My charts more complicated and have tons of points, I need to get Y value through X.

How can I do this?

TaW
  • 53,122
  • 8
  • 69
  • 111
Bigfoot Bull
  • 25
  • 2
  • 7
  • This is not really possible unless you actually have one or more points at the given x-value. All you can do is try to interpolate the y-value by simple math. Note that line charts allow you to move to and fro with the lines so any x-value can have many y-values and a line through it may cross many of the chart lines. - For the interpolation you need to find the two neighbouring points and work with them. The math is really trivial. – TaW Sep 07 '17 at 09:08
  • I thought if line was already calculated and drawn I can get value of Y on X even without a point there. I want to get Y value of each series on certain X to summarize them later and create 1 chart, like total balance. – Bigfoot Bull Sep 07 '17 at 09:13
  • Yes, if it really is just a line and not a curve you can calculate any point on it, as I said. But this means that you need to know the endpoints of that line. From there it is simple and if you know that the x-vlues will always move forward this is not hard at all.. – TaW Sep 07 '17 at 09:16

1 Answers1

5

The problem boils down to two tasks:

  • Finding the neighbouring points for an x-value
  • Interpolating their y-values for the given x-value.

If the x-values are indeed steadily increasing this should solve both:

double interpolatedY(Series s, double xval)
{
    DataPoint pPrev = s.Points.Last(x => x.XValue <= xval);
    DataPoint pNext = s.Points.First(x => x.XValue >= xval);

    if (pPrev == pNext) return pPrev.YValues[0];

    return pPrev.YValues[0] + (pNext.YValues[0] - pPrev.YValues[0])
        * (xval  - pPrev.XValue)/ (pNext.XValue - pPrev.XValue); 
}

It uses Linq to find the previous and next datapoint and then uses simple math to find the interpolated value.

Note that most checks are omitted!

Here I have added an identical point series and a third one to add the interpolated values:

enter image description here

To convert between chart pixels and values there are Axis functions ValueToPixelPosition and PixelPositionToValue, btw.

TaW
  • 53,122
  • 8
  • 69
  • 111