Get Y-value of a graph in C#

2019-06-05 01:30发布

In C#, how can I get the Y-value of a point of a chart series, knowing its X-value which is of type DateTime? I do not know the index of the series, only know their names.

Below are my codes. In fact I did a simulation of stock prices over time. Now I want to add the series "Service dates" to mark the specific date points of the simulation. What I need now is to set the colpos to the Y-value of the series whose name is given by colinfo.colptf

Or could you just show me how to get the index of the chart1.series[colinfo.colptf]?

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
        if (radioButton1.Checked == true)
        {
            radioButton2.Checked = false;
            radioButton3.Checked = false;
            radioButton4.Checked = false;
            clearseries(chart1, "Service dates");
            chart1.Series.Add("Service dates");
            chart1.Series["Service dates"].Color = Color.Red;
            chart1.Series["Service dates"].ChartType = SeriesChartType.Point;
            foreach (var simul in simulations)
                foreach (var colinfo in simul.VPdates)
                {
                    double colpos = chart1.Series[colinfo.colptf].Points.First(x => x.XValue == colinfo.coldate.ToOADate()).YValues[0];
                    addpoint(colinfo.coldate, colpos, colinfo.colstring, chart1.Series["Service dates"]);
                }
        }
}

标签: c# charts
1条回答
Lonely孤独者°
2楼-- · 2019-06-05 02:09

You could use

var collection = chart1.Series.Select(series => series.Points.Where(point => point.XValue == 0).ToList()).ToList();

This will get you a list of series with all points that are at the specified X coordinate.

If you want all the datapoints in 1 list you can now use

List<DataPoint> points = new List<DataPoint>();
collection.ForEach(series => series.ForEach(points.Add));

Getting the Y value from a DataPoint is simply using YValues, which returns an array of Y values. I assume you only assign 1 Y value to each point, so you can just take the 1st index, which is [0].

So getting the 1st points 1st Y value would be:

double yVal = points[0].YValues[0];
查看更多
登录 后发表回答