0

I have a chart with two series that share the same X axis values. I want to subtract the Y values and create a new series.

There are two ways I've tried so far:

  1. Convert the points on the chart and put them into an array and subtract them:

       double[] arrayX = new double[chart2.Series[0].Points.Count()];
       double[] arrayY = new double[chart2.Series[0].Points.Count()];
       double[] arrayResult = { };
    
        for (int i = 0; i < chart2.Series[0].Points.Count(); i++)
        {               
            arrayX[i] = chart2.Series[0].Points[i].XValue;
            arrayY[i] = chart2.Series[0].Points[i].YValues[0];
        }
    

The issue with this is that this only gets the X Values from the first series and leaves out the second series X Values.

  1. When I add the points to the chart I used this:

    chart2.Series[SplitListBox.Items[0].ToString()].Points.AddXY(e, firstval);  
    chart2.Series[SplitListBox.Items[1].ToString()].Points.AddXY(e, firstval);  
    

Both of which are in separate loops. I was going to use 2 array to catch the points (e,firstval) for each loop but I don't know how to subtract the two from each other and still keep the values that exist in one series but not in the other.

TaW
  • 53,122
  • 8
  • 69
  • 111
Sewder
  • 754
  • 3
  • 11
  • 37

1 Answers1

1

After creating the new Series SDelta to your liking you can call a simple function to fill it like this:

void PlotDelta(Chart chart, Series S1, Series S2, Series SDelta)
{
    for (int i = 0; i < S1.Points.Count; i++)
    {
        if ( i < S2.Points.Count)
        {
            DataPoint dp1 = S1.Points[i];
            DataPoint dp2 = S2.Points[i];
            if (!dp1.IsEmpty && !dp2.IsEmpty)
                SDelta.Points.AddXY(dp1.XValue, dp2.YValues[0] - dp1.YValues[0]);
        }
    }

You may want to improve the error handling for cases of different point counts or emtpy points..

Here is a testbed:

    private void button1_Click(object sender, EventArgs e)
    {
        chart1.Series.Clear();
        chart1.Series.Add(new Series { Name = "Cos", ChartType = SeriesChartType.Line });
        chart1.Series.Add(new Series { Name = "Sin", ChartType = SeriesChartType.Line });
        chart1.Series.Add(new Series { Name = "Delta", ChartType = SeriesChartType.Line });

        for (int i = 0; i < 100; i++ )
        {
            chart1.Series["Cos"].Points.AddXY(i, Math.Cos(i / Math.PI));
            chart1.Series["Sin"].Points.AddXY(i, Math.Sin(i / Math.PI));
        }

        PlotDelta(chart1, chart1.Series["Cos"], chart1.Series["Sin"],
                          chart1.Series["Delta"]);
    }

enter image description here

Of course you could integrate the creation of the delta series in the function; but you would have to pass in any properties you may want to vary like Color, ChartType etc..

TaW
  • 53,122
  • 8
  • 69
  • 111