ScottPlot.NET
GitHub Repo stars

Dynamically Generated Functions

When a function cannot be represented as a static method (e.g., one that requires custom parameters) it can be represented as variable of type Func<double, double> and plotted accordingly.

ScottPlot.Plot myPlot = new();

static double LogNormalDist(double x, double a, double b)
{
    double expNum = Math.Log(x / a);
    double exp = Math.Exp(-(expNum * expNum) / (2 * b * b));
    double y = Math.Sqrt(2 * Math.PI) * b * x * exp;
    return double.IsNaN(y) ? 0 : y;
}

double[] testValues = Generate.Range(0.8, 1.2, 0.05);
Color[] colors = new ScottPlot.Colormaps.MellowRainbow().GetColors(testValues.Length);
for (int i = 0; i < testValues.Length; i++)
{
    double testValue = testValues[i];
    var myFunc = new Func<double, double>((x) => LogNormalDist(x, testValue, 0.5));
    var funcPlot = myPlot.Add.Function(myFunc);
    funcPlot.LegendText = $"{testValue:0.00}";
    funcPlot.LineWidth = 2;
    funcPlot.LineColor = colors[i];
}

myPlot.ShowLegend();
myPlot.Legend.Orientation = Orientation.Horizontal;

myPlot.Axes.SetLimitsX(-0.5, 4);
myPlot.Axes.SetLimitsY(-0.8, 2);

myPlot.SavePng("demo.png", 400, 300);
This recipe is one of many in the Function category