旅行好きなソフトエンジニアの備忘録

プログラミングや技術関連のメモを始めました

【WPF】 OxyPlotでグラフを描画する簡単な例

WPFでグラフを描きたい時はOxyPlotを利用しているのですが、頻繁に使うわけでもないため、使う度に同じことを調べる事態になってしまっています。そのため、OxyPlotの使い方に関する単純な例をメモしておきます。

1. NuGetからOxyPlot.Wpfをインストールする

2. (XAML)Windowにoxyを追加する & GridにPlotを追加する

<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Test"
        mc:Ignorable="d"
        xmlns:oxy="http://oxyplot.org/wpf"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <oxy:Plot Name="PlotExample" Title="Example">
            <oxy:Plot.Series>
                <oxy:LineSeries/>
            </oxy:Plot.Series>
        </oxy:Plot>        
    </Grid>
</Window>

3. Axisを定義し、データをセットする

// これらのusingが必要
using OxyPlot;
using OxyPlot.Wpf;


// X軸の定義
LinearAxis xAxis = new LinearAxis
{
    Position = OxyPlot.Axes.AxisPosition.Bottom,
    Title = "x",
    Unit = "x unit"
};
PlotExample.Axes.Add(xAxis);

// Y軸の定義
LinearAxis yAxis = new LinearAxis
{
    Position = OxyPlot.Axes.AxisPosition.Left,
    Title = "y",
    Unit = "y unit"
};
PlotExample.Axes.Add(yAxis);

// ItemsSourceにデータをセットする
var points = new List<DataPoint>() { new DataPoint(0.0, 1.0), new DataPoint(1.0, 2.0), new DataPoint(2.0, 3.0) };
PlotExample.Series[0].ItemsSource = points;
// Plotを更新する
PlotExample.InvalidatePlot();


f:id:ni4muraano:20170715160706p:plain