Search code examples
c#wpfplotoxyplot

How to plot LineSeries using the OxyPlot library on the WPF UI framework


I am trying to plot my data using OxyPlot. I want to plot two lines in my graph but I am not sure how to provide the plot with data. This is how my XAML file looks like:

<oxy:Plot Name="Plot1">
  <oxy:Plot.Series>
    <oxy:LineSeries ItemsSource="{Binding Graph1}"/>
    <oxy:LineSeries ItemsSource="{Binding Graph2}"/>
  </oxy:Plot.Series>
</oxy:Plot>

My question is how can I plot two lines in the same graph while using LineSeries?


Solution

  • Usually you don't add the LineSeries directly to a PlotView but to a PlotModel which is then bound to the Plot View.

    The C# code could look like this:

            PlotModel pm = new PlotModel();
    
            var s1 = new LineSeries();
    
            for (int i = 0; i < 1000; i++)
            {
                double x = Math.PI * 10 * i / (1000 - 1);
                s1.Points.Add(new DataPoint(x, Math.Sin(x)));
            }
    
            pm.Series.Add(s1);
    
            var s2 = new LineSeries();
    
            for (int i = 0; i < 1000; i++)
            {
                double x = Math.PI * 10 * i / (1000 - 1);
                s2.Points.Add(new DataPoint(x, Math.Cos(x)));
            }
    
            pm.Series.Add(s2);
    
            Plot1.Model = pm; 
    

    The binding to Plot1 can of course also be done in XAML. If your DataContext provides the PlotModel via a property 'MyModel', it would look like this:

    <oxyplot:PlotView Model="{Binding MyModel}"></oxyplot:PlotView>