Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the Y value of a line chart based on cursor position

I'm new to charts and have a line chart that looks as thus.

https://s15.postimg.org/vzl71faqj/Untitled.png

The vertical line is where the cursor is and updates via mousemove rather than mouseclick.

As the title suggests what I want to do is access the Y value at the point at which the vertical line and the 'data line' intersect.

I've tried this - Get Y value of series from the X Cursor position where a ChartArea is clicked on but unless I'm missing something it just doesn't work, it either returns the first or the last value in the series depending on which datapoint you use.

I've tried hittestresult, that only seems to work if you're 'touching' the data line itself.

Any ideas?

like image 222
user1006221 Avatar asked Nov 17 '25 16:11

user1006221


1 Answers

Since you didn't show us any code and didn't answer my questions I can only assume that your chart doesn't have valid, i.e. numeric x-values.

This means the the x-values are all 0 and can't be used for anything: neither for setting a zoom range, not for formatting axis or other labels and also not for finding the DataPoints at an x-position.

This can be called 'implicitly indexed'. The result is similar to explicitly indexed charts, which results from setting the IsXValueIndexed of a Series to true: The DataPoints are lined up in a row and all are displayed at the same distance.

This is usually not what one wants and I really suggest you fix it by adding the DataPoints not like this:

for (int i = 0; i < count; i++) chart1.Series[0].Points.AddY(someYValue);

but maybe like this:

for (int i = 0; i < count; i++) chart1.Series[0].Points.AddXY(i, someYValue);

Then the linked answer will work just fine.

But just to show how you could workaround here is how to find the two closest points in an indexed chart.

Note that it uses a function, (actually two) that calculates the pixel rectangle of the inner plot postion. You can find them here or here..:

private void chart1_MouseMove(object sender, MouseEventArgs e)
{
    ChartArea ca = chart1.ChartAreas[0];
    Series S = chart1.Series[0];
    RectangleF rf = InnerPlotPositionClientRectangle(chart1, ca);
    float px = (float)( (e.X - rf.X) * S.Points.Count / rf.Width );

    int p0 = (int)px;  // previous point
    int p1 = p0 + 1;   // next point

    if (p0 >= 0 &&  p0 < S.Points.Count)
        Console.WriteLine( "DataPoint # " + p0 + " has a y-value of " + 
                           S.Points[p0].YValues[0].ToString("0.00"));
    //..
}

It will work but you really should correct the way you add the data points!

like image 128
TaW Avatar answered Nov 19 '25 05:11

TaW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!