Search code examples
c#windowswinformsplotoxyplot

How do I graph a custom function in OxyPlot?


I'm trying to graph a trend line for my data. Is there anyway to define a custom function? The closest I've seen is with in the Hello Windows Forms example here: http://www.oxyplot.org/doc/HelloWindowsForms.html

Code:

namespace WindowsFormsApplication1
{
    using System;
    using System.Windows.Forms;

    using OxyPlot;
    using OxyPlot.Series;

    public partial class Form1 : Form
    {
        public Form1()
        {
            this.InitializeComponent();
            var myModel = new PlotModel("Example 1");
            myModel.Series.Add(new FunctionSeries(Math.Cos, 0, 10, 0.1, "cos(x)"));
            this.plot1.Model = myModel;
        }
    }
}

In the example, they use Cosine. What if I needed to define a custom multivariable equation?

Edit: I've found a partial answer.

Use a Lambda series:

new FunctionSeries( x => a*x*x*x + b*x*x + c*x + d, .... )

Src: https://oxyplot.codeplex.com/discussions/439064

Still don't know how to do a multivariable equation though.


Solution

  • Here are the example picture: the image from the function below And this is the code:

        //your function based on x,y
        public double getValue(int x, int y)
        {
            return (10 * x * x + 11 * x*y*y  + 12*x*y );
        }
    
        //setting the values to the function
        public FunctionSeries GetFunction()
        { 
            int n = 100;
            FunctionSeries serie = new FunctionSeries();
            for (int x = 0; x < n; x++)
            {
                for (int y = 0; y < n; y++)
                {
                    //adding the points based x,y
                    DataPoint data = new DataPoint(x, getValue(x,y));
    
                    //adding the point to the serie
                    serie.Points.Add(data);
                }
            }
            //returning the serie
            return serie;
        }
    
        //setting all the parameters of the model
        public void graph()
        {
            model = new PlotModel { Title = "example" };
            model.LegendPosition = LegendPosition.RightBottom;
            model.LegendPlacement = LegendPlacement.Outside;
            model.LegendOrientation = LegendOrientation.Horizontal;
    
            model.Series.Add(GetFunction());
            var Yaxis = new OxyPlot.Axes.LinearAxis();
            OxyPlot.Axes.LinearAxis XAxis = new OxyPlot.Axes.LinearAxis { Position = OxyPlot.Axes.AxisPosition.Bottom, Minimum = 0, Maximum = 100 };
            XAxis.Title = "X";
            Yaxis.Title = "10 * x * x + 11 * x*y*y  + 12*x*y";
            model.Axes.Add(Yaxis);
            model.Axes.Add(XAxis);
            this.plot.Model = model;
        }
    
        //on click on the button 3 then show the graph
        private void button3_Click(object sender, EventArgs e)
        {
            graph();
        }