StackedBarSampleDemo 完整原始碼
using System;
using System.Drawing;
using System.Collections;
using ZedGraph;
namespace ZedGraph.Demo
{
public class StackedBarSampleDemo : DemoBase
{
public StackedBarSampleDemo() : base("Code Project Stacked Bar Chart Sample", "Stacked Bar Sample", DemoType.Tutorial)
{
GraphPane myPane = base.GraphPane;
// 標題與軸標籤
myPane.Title.Text = "Cat Stats";
myPane.XAxis.Title.Text = "Big Cats";
myPane.YAxis.Title.Text = "Population";
// 資料
string[] labels = { "Panther", "Lion", "Cheetah", "Cougar", "Tiger", "Leopard" };
double[] y = { 100, 115, 75, 22, 98, 40 };
double[] y2 = { 120, 175, 95, 57, 113, 110 };
double[] y3 = { 204, 192, 119, 80, 134, 156 };
// 三組堆疊柱狀圖
BarItem myCurve = myPane.AddBar("Here", null, y, Color.Red);
myCurve.Bar.Fill = new Fill(Color.Red, Color.White, Color.Red);
myCurve = myPane.AddBar("There", null, y2, Color.Blue);
myCurve.Bar.Fill = new Fill(Color.Blue, Color.White, Color.Blue);
myCurve = myPane.AddBar("Elsewhere", null, y3, Color.Green);
myCurve.Bar.Fill = new Fill(Color.Green, Color.White, Color.Green);
// X 軸設定
myPane.XAxis.IsTicsBetweenLabels = true;
myPane.XAxis.TextLabels = labels;
myPane.XAxis.Type = AxisType.Text;
// 關鍵:設定堆疊模式
myPane.BarType = BarType.Stack;
base.ZedGraphControl.AxisChange();
}
}
}
關鍵點說明
- 三組資料
y, y2, y3 分別代表不同類別的人口數。
- 每組使用
AddBar 加入,並設定 Bar.Fill 為三色漸層 (主色-白-主色) 營造 3D 效果。
myPane.BarType = BarType.Stack 啟用堆疊模式,ZedGraph 會自動累加 Y 值繪製。
- X 軸採用文字標籤模式,
IsTicsBetweenLabels = true 讓群集柱條置中。