This is the code that Oxyplot official page shows. namespace WpfApplication2
{
using System.Collections.Generic;
using OxyPlot;
public class MainViewModel
{
public MainViewModel()
{
this.Title = "Example 2";
this.Points = new List<DataPoint>
{
new DataPoint(0, 4),
new DataPoint(10, 13),
new DataPoint(20, 15),
new DataPoint(30, 16),
new DataPoint(40, 12),
new DataPoint(50, 12)
};
}
public string Title { get; private set; }
public IList<DataPoint> Points { get; private set; }
}
}
This is the XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:oxy="http://oxyplot.codeplex.com"
xmlns:local="clr-namespace:WpfApplication2"
Title="Example 2 (WPF)" Height="350" Width="525">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<oxy:Plot Title="{Binding Title}">
<oxy:Plot.Series>
<oxy:LineSeries ItemsSource="{Binding Points}"/>
</oxy:Plot.Series>
</oxy:Plot>
</Grid>
</Window>
The example just works fine and shows 6 points on the graph. What I want to do is plotting a graph of the data which comes through Serial Port. I want to add new points to graph in the DispatcherTimer's Tick event. To eliminate any misunderstanding, My question's scope is about oxyplot,(not, for example, usage of timer event should be included in answer.) Thank you in advance.
Try this code.
XAML:
<oxy:PlotView Model="{Binding DataPlot}"/>
MainViewModel:
public PlotModel DataPlot { get; set; }
private double _xValue = 1;
public MainViewModel()
{
DataPlot = new PlotModel();
DataPlot.Series.Add(new LineSeries());
var dispatcherTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 1) };
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
Dispatcher.CurrentDispatcher.Invoke(() =>
{
(DataPlot.Series[0] as LineSeries).Points.Add(new DataPoint(_xValue, Math.Sqrt(_xValue)));
DataPlot.InvalidatePlot(true);
_xValue ++;
});
}
If you don´t want to accumulate all points from start to end in chart, just use this after adding every new point:
if ((DataPlot.Series[0] as LineSeries).Points.Count > 10) //show only 10 last points
(DataPlot.Series[0] as LineSeries).Points.RemoveAt(0); //remove first point
If you want a better flow of the chart (this one updates every second) I recommend using Stopwatch
, putting code that add points into own method and starting that method in thread in constructor. Then i.e. use Stopwatch.ElapsedMilliseconds
as x-value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With