LiveCharts线性图表的绘制

因为官方没什么文档,示例也不太行就记一下怎么用(

使用到的控件是CartesianChart

因为只是实验性代码所以看起来会很屎

UI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<Window x:Class="WPF_T.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:ui="http://schemas.modernwpf.com/2019"
xmlns:wpf="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
ui:WindowHelper.UseModernWindowStyle="True"
mc:Ignorable="d"
WindowStartupLocation="CenterScreen"
Title="MainWindow"
Height="450"
Width="800"
DataContext="MainWindow">
<Grid>

<wpf:CartesianChart Name="Chart"
LegendLocation="Right" Margin="86,49,112,49">
<wpf:CartesianChart.AxisY>
<wpf:Axis Name="YAxis" Title="好耶"></wpf:Axis>
</wpf:CartesianChart.AxisY>
<wpf:CartesianChart.AxisX>
<wpf:Axis Name="XAxis"></wpf:Axis>
</wpf:CartesianChart.AxisX>
</wpf:CartesianChart>
<Rectangle HorizontalAlignment="Left" Height="337" Margin="86,0,0,0" Stroke="Black" VerticalAlignment="Center" Width="602"/>

</Grid>
</Window>

控件控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Media;
using LiveCharts;
using LiveCharts.Wpf;

namespace WPF_T
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();

//横坐标值初始化
XAxis.Labels = new List<string>();
//纵坐标数值格式化
YAxis.LabelFormatter = data => data.ToString("F2");
//纵坐标初始范围设置
YAxis.MaxValue = 2;
YAxis.MinValue = -2;

//线性数据初始化
var lineseries = new LineSeries
{
//点坐标显示
DataLabels = false,
//线条下方的填充
Fill = new SolidColorBrush(Color.FromArgb(20, 0, 0, 255)),
//数据名
Title = "test",
//数据值
Values = new ChartValues<int>()
};
//添加数据
Chart.Series.Add(lineseries);
//动态绘图
Task.Run(async () =>
{
var a = 0;
var rd = new Random();
for (var i = 0; i < 5;i++)
{
//纵坐标数据
Chart.Series[0].Values.Add(rd.Next(-2,2));
//横坐标
XAxis.Labels.Add(a++.ToString());
await Task.Delay(1000);
}
});
}
}
}

效果图

SC-2021-6-17.png