使用Visifire完成的分组图示效果,主要是代码,代码如下,希望对大家有用
class TestData {
public string Txt1 { get; set; }//保存一级分类
public string Txt2 { get; set; }//保存二级分类
public int Value { get; set; }
}
List<TestData> datas;
public Form1()
{
InitializeComponent();
//初始化数据
datas = new List<TestData>
{
new TestData{Txt1="西安",Txt2="西安1",Value=22},
new TestData{Txt1="西安",Txt2="西安2",Value=23},
new TestData{Txt1="西安",Txt2="西安3",Value=24},
new TestData{Txt1="西安",Txt2="西安4",Value=25},
new TestData{Txt1="宝鸡",Txt2="宝鸡5",Value=25},
new TestData{Txt1="宝鸡",Txt2="宝鸡6",Value=25},
new TestData{Txt1="宝鸡",Txt2="宝鸡7",Value=25}
};
CreateChart();
}
/// <summary>
/// Function to create a chart
/// </summary>
public void CreateChart()
{
Chart chart = new Chart();//创建图表
chart.View3D = true;//3D显示
Title title = new Title();//创建标题
title.Text = "统计测试信息";
chart.Titles.Add(title);
//定义一级分类显示颜色
SolidColorBrush[] brushes = new SolidColorBrush[]{
new SolidColorBrush(Colors.Red),
new SolidColorBrush(Colors.Green)
};
DataSeries dataSeries = new DataSeries();
dataSeries.RenderAs = RenderAs.Column;//柱形图
int n = 0;
//按一级分类分组
foreach (var d in datas.GroupBy(d => d.Txt1).ToList())
{
var subList = d.ToList();//获取一级分类下的数据
for (var i = 0; i < subList.Count; i++)
{
DataPoint dataPoint = new DataPoint();
dataPoint.Color = brushes[n];
dataPoint.AxisXLabel = subList[i].Txt2;
dataPoint.YValue = subList[i].Value;
dataSeries.DataPoints.Add(dataPoint);
if (i == 0)
{
//显示一级图例
dataPoint.Name = d.Key;
dataPoint.ShowInLegend = true;
}
else
{
dataPoint.ShowInLegend = false;
}
}
n++;
}
dataSeries.ShowInLegend = true;//显示图例
chart.Series.Add(dataSeries);
elementHost1.Child = chart;
}