Search code examples
c#chartsdata-visualizationderivative

Chart Series First Derivative


I am plotting a chart using System.Windows.Forms.DataVisualization.Charting I've populated the series with a bunch of x and y points and I want to be able to plot the derivative as well. Does anyone know of a simple way to do so?

Alternatively, if there was a way to get the corresponding function of the set of xy points that would be helpful too.

Thank you.

Series Population:

chart_TitrationData.ChartAreas[0].AxisX.Title = "Volume (mL)";
chart_TitrationData.ChartAreas[0].AxisY.Title = "pH";
chart_TitrationData.Series.Add(_SelectedTitration.TitrationID);        
chart_TitrationData.Series[_SelectedTitration.TitrationID].ChartType = SeriesChartType.Spline;          
chart_TitrationData.Series[_SelectedTitration.TitrationID].MarkerStyle = MarkerStyle.Circle;              
chart_TitrationData.Series[_SelectedTitration.TitrationID].XValueType = ChartValueType.Double;           
chart_TitrationData.Series[_SelectedTitration.TitrationID].YValueType = ChartValueType.Double;         
chart_TitrationData.Series[_SelectedTitration.TitrationID].IsVisibleInLegend = true;
foreach (var data in _SelectedTitration.TitrationData)
{     
    chart_TitrationData.Series[_SelectedTitration.TitrationID].Points.AddXY(data.XPoint, data.YPoint);
}

Solution

  • There are Statistical Formulas built-in but none for derivatives. Not even in the other function class, the Financial Formulas

    So you have to calculate them yourself.

    For a given Series s0 the 1st derivative can be calculated from differences:

    for (int i = 1; i < s0.Points.Count; i++)
    {
        s1.Points.AddXY(s0.Points[i].XValue, (s0.Points[i].YValues[0] - 
                                              s0.Points[i-1].YValues[0]) / scale);
    }
    

    This simple test..:

    double scale = 100;
    for (int i = 0; i < 1000; i++)
    {
        s0.Points.AddXY(i, Math.Sin(i / scale)); 
    }
    

    results, as expected..:

    enter image description here

    If the x-values are not so evenly spaced you should calculate the full difference quotient by diving by the individual steps:

    double step = s0.Points[i].XValue -  s0.Points[i-1].XValue;
    

    Also: The above is a slight simplification. For better precision one ought to use x-step/2 and x+step/2 as x-values with the respective interpolated y-values. And omit both first and last point in s2..