如何向OxyPlot添加新的数据点?

4

这是Oxyplot官方页面展示的代码。

命名空间为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; }
    }
}

这是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>

这个示例很好用,可以在图表上显示6个点。 我想要做的是绘制通过串行端口传来的数据的图表。我想在DispatcherTimer的Tick事件中添加新的点到图表上。为了消除任何误解,我的问题范围是关于oxyplot的(不是例如,定时器事件的使用应该包含在答案中)。谢谢。

1个回答

9
请尝试以下代码。
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 ((DataPlot.Series[0] as LineSeries).Points.Count > 10) //show only 10 last points
    (DataPlot.Series[0] as LineSeries).Points.RemoveAt(0); //remove first point

如果您希望图表的流畅性更好(此图表每秒更新一次),我建议使用计时器,将添加数据点的代码放在自己的方法中,并在构造函数中开启线程来运行该方法。然后将计时器.ElapsedMilliseconds用作x值。


你的回答让我不再寻找,感谢你,英雄。 - smoothumut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接