WPF图表Live Chart(三)柱状图
前面介绍了Live Chart的基础和设置,接下介绍一下如何实现一个柱状图。该柱状图主要实现打开多个文件,读取文件的多个数据并显示的功能。
效果预览
打开多个数据文件,同时读取文件的文件的大小,文件的的温度数据,分两个Y轴显示,同时有各自的单位。
前台代码
<Grid >
<lvc:CartesianChart Series="{Binding SeriesCollection}" LegendLocation="Top">
<lvc:CartesianChart.AxisX>
<lvc:Axis Title="fielname" Labels="{Binding Labels}" FontSize="14"></lvc:Axis>
</lvc:CartesianChart.AxisX>
<lvc:CartesianChart.AxisY>
<lvc:Axis x:Name="axisT" LabelFormatter="{Binding FormatterT}" Foreground="DodgerBlue" FontSize="14" />
<lvc:Axis x:Name="axisS" LabelFormatter="{Binding FormatterS}" Foreground="IndianRed" Position="RightTop" FontSize="14" />
</lvc:CartesianChart.AxisY>
</lvc:CartesianChart>
<Button x:Name="button_open" Content="open" HorizontalAlignment="Right" VerticalAlignment="Top" Width="40" Click="button_openClick"
Background="{x:Null}" BorderBrush="{DynamicResource {x:Static SystemColors.HotTrackBrushKey}}"
Foreground="{DynamicResource {x:Static SystemColors.HotTrackBrushKey}}" Opacity="0.5" Height="20"/>
</Grid>
后台代码
public partial class MainWindow : Window
{
public Func<double, string> FormatterT { get; set; }
public Func<double, string> FormatterS { get; set; }
public SeriesCollection SeriesCollection { get; set; }
public string[] Labels { get; set; }
List<double> filesize = new List<double>();
List<string> filenames = new List<string>();
List<double> temperature = new List<double>();
//新建一条文件大小的柱状图
ColumnSeries sizeseries = new ColumnSeries();
//新建一条温度的柱状图
ColumnSeries templeseries = new ColumnSeries();
public MainWindow()
{
InitializeComponent();
//添加两个纵坐标的单位
FormatterT = value => value + "C°";
FormatterS = value => value + "KB";
templeseries.Title = "temp";
//温度的柱状图依赖于第一条纵坐标
templeseries.ScalesYAt = 0;
axisT.Title = "temp/C°";
sizeseries.Title = "size";
//文件大小的柱状图依赖于第二条纵坐标
sizeseries.ScalesYAt = 1;
axisS.Title = "size/KB";
SeriesCollection = new SeriesCollection { };
SeriesCollection.Add(templeseries);
SeriesCollection.Add(sizeseries);
//绑定数据
DataContext = this;
}
public void button_openClick(object sender, RoutedEventArgs e)
{
filenames.Clear();
filesize.Clear();
temperature.Clear();
OpenFileDialog open_files = new OpenFileDialog();
//打开多个文件
open_files.Multiselect = true;
if (open_files.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (string file in open_files.FileNames)
{
FileInfo MyFileInfo = new FileInfo(file);
//获取文件的大小
filesize.Add((int )MyFileInfo.Length/1024 );
//获取文件的名称
filenames.Add (System.IO.Path.GetFileNameWithoutExtension(file));
//通过正则表达式获取文件中的数据信息
StreamReader sr = new StreamReader(file);
string pattern = @"DHT11 temp:([0-9]+(.[0-9]{1,3})?),";
string line;
while ((line = sr.ReadLine()) != null)
{
Regex r = new Regex(pattern , RegexOptions.None);
Match mc = r.Match(line );
string tempStr = mc.Groups[1].Value;
temperature.Add (Convert.ToDouble (tempStr));
break;
}
sr.Close();
}
}
Labels = filenames.ToArray();
templeseries.Values = new ChartValues<double>(temperature);
sizeseries.Values = new ChartValues<double>(filesize);
}
}