使用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;
}