Search code examples
delphiteechart

TeeChart Get Series Y value or index by given X value


I have the following problem: I am using Delphi XE3 with TeeChart and I'd like to retrieve a Y value or the value index of a serie by a given X value. My serie is a time series with dates on the X axis. I know the date on the chart and I want to display the nearest corresponding Y value to this date.

Is there any method or function of the TChart or TChartSeries component to achieve this? Or do I need to iterate through the series until I reached the selected date?

It is not possible to use the CursorPostion methods, because the cursor could be anywhere.

Thanks in advance for your help.


Solution

  • You can use Locate method of TChartValueList to get index of appropriate data entry.

    Example from help:

    tmp:=LineSeries1.XValues.Locate(EncodeDate(2007,1,1));
    if tmp<>-1 then ...
    

    Edit: This method works for exact coincidence.

    If your X-values are sorted (default mode), then you can use binary search in XValues to find the closest value quickly.
    For example, we can modify this code to return the closest value index instead of -1, or use linear interpolation (if applicable) for two neighbor values.

      //assumes A.Order = loAscending (default)
      function FindClosestIndex(const Value: Double; A: TChartValueList): Integer;
      var
        ahigh, j, alow: integer;
      begin
        // extra cases
        if A.Count = 0 then
          Exit(-1);
        if Value <= A.First then
          Exit(0);
        if Value >= A.Last then
          Exit(A.Count - 1);
    
        // binary search
        alow := 0;
        ahigh := A.Count - 1;
        while ahigh - alow > 1 do begin
          j := (ahigh + alow) div 2;
          if Value <= A[j] then
            ahigh := j
          else
            alow := j;
        end;
    
        // choose the closest from ahigh, alow
        Result := ahigh - Ord(A[ahigh] - Value >= Value - A[alow])
      end;