一、LiveCharts简介
LiveCharts 是一个用于 .NET 平台的开源图表库,它提供了丰富的图表类型和交互功能,可以用于创建动态和交互式的数据可视化。LiveCharts 支持多种图表类型,包括折线图、柱状图、饼图等,可以轻松地集成到 WPF、WinForms 和 Xamarin 应用程序中。用户可以通过 LiveCharts 创建各种各样的数据图表,以直观地展示数据,并支持对图表进行动态更新和交互操作。
- LiveCharts2源码
- LiveCharts2文档
二、安装依赖包
2.1 右键单击引用,然后管理 NuGet 程序包
2.2 搜索LiveCharts,安装LiveCharts和LiveCharts.Wpf
三、代码实现
3.1 CartesianChartWindow.xaml
<Window x:Class="wpf_demo.CartesianChartWindow"
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:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
xmlns:local="clr-namespace:wpf_demo"
mc:Ignorable="d"
Title="折线图" Height="600" Width="800" Loaded="WindowLoaded">
<Grid>
<VirtualizingStackPanel>
<TextBlock Margin="10 10 0 0" Text="图表1:静态数据"/>
<StackPanel Width="700" Height="200">
<lvc:CartesianChart LegendLocation="Bottom" Height="200">
<lvc:CartesianChart.Series>
<lvc:LineSeries Fill="LightGreen" Stroke="Green" Values="12,34,55,40,30,54,26" Title="产量" DataLabels="True"/>
</lvc:CartesianChart.Series>
</lvc:CartesianChart>
</StackPanel>
<TextBlock Margin="10 80 0 0" Text="图表2:后端动态初始化数据"/>
<StackPanel Width="700" Height="200">
<lvc:CartesianChart x:Name="chartDynamic" LegendLocation="Bottom" Height="200" />
</StackPanel>
</VirtualizingStackPanel>
</Grid>
</Window>
注意:在使用的页面中,引入LiveChart.Wpf
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
3.2 CartesianChartWindow.xaml.cs
using LiveCharts.Wpf;
using LiveCharts;
using System.Windows;
using System.Windows.Media;
namespace wpf_demo
{
public partial class CartesianChartWindow : Window
{
public CartesianChartWindow()
{
InitializeComponent();
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
InitChartDynamic();
}
//给图表赋值
private void InitChartDynamic()
{
List<double> dataList = [254, 568, 563, 482, 263, 104];//从数据库取
ChartValues<double> chartValues = new ChartValues<double>(dataList);
SeriesCollection series = new SeriesCollection()
{
new LineSeries
{
Values = chartValues,
Fill=new SolidColorBrush(Colors.IndianRed),
Title = "销量",
DataLabels = true //显示数据标签
},
};
this.chartDynamic.Series = series;
}
}
}
四、效果图
参考资料:wpf中的图表LiveCharts,本文主要说明CartesianChart和PieChart的用法