BarChartSampleDemo 完整原始碼
using System;
using System.Drawing;
using System.Collections;
using ZedGraph;
namespace ZedGraph.Demo
{
public class BarChartSampleDemo : DemoBase
{
public BarChartSampleDemo() : base("Code Project Bar Chart Sample", "Bar Chart Sample", DemoType.Tutorial)
{
GraphPane myPane = base.GraphPane;
// 標題與軸標籤
myPane.Title.Text = "My Test Bar Graph";
myPane.XAxis.Title.Text = "Label";
myPane.YAxis.Title.Text = "My Y Axis";
// 資料準備
string[] labels = { "Panther", "Lion", "Cheetah", "Cougar", "Tiger", "Leopard" };
double[] y = { 100, 115, 75, 22, 98, 40 };
double[] y2 = { 90, 100, 95, 35, 80, 35 };
double[] y3 = { 80, 110, 65, 15, 54, 67 };
double[] y4 = { 120, 125, 100, 40, 105, 75 };
// 三組柱狀圖
BarItem myBar = myPane.AddBar("Curve 1", null, y, Color.Red);
myBar.Bar.Fill = new Fill(Color.Red, Color.White, Color.Red);
myBar = myPane.AddBar("Curve 2", null, y2, Color.Blue);
myBar.Bar.Fill = new Fill(Color.Blue, Color.White, Color.Blue);
myBar = myPane.AddBar("Curve 3", null, y3, Color.Green);
myBar.Bar.Fill = new Fill(Color.Green, Color.White, Color.Green);
// 一組折線圖 (混合圖表)
LineItem myCurve = myPane.AddCurve("Curve 4", null, y4, Color.Black, SymbolType.Circle);
myCurve.Line.Fill = new Fill(Color.White, Color.LightSkyBlue, -45F);
myCurve.Symbol.Size = 8.0F;
myCurve.Symbol.Fill = new Fill(Color.White);
myCurve.Line.Width = 2.0F;
// X 軸文字標籤與刻度模式
myPane.XAxis.IsTicsBetweenLabels = true;
myPane.XAxis.TextLabels = labels;
myPane.XAxis.Type = AxisType.Text;
// 背景填充
myPane.AxisFill = new Fill(Color.White, Color.FromArgb(255, 255, 166), 90F);
myPane.PaneFill = new Fill(Color.FromArgb(250, 250, 255));
base.ZedGraphControl.AxisChange();
}
}
}
程式碼結構說明
- 建立四組資料陣列 (三柱狀、一折線)。
- 使用
AddBar 加入柱狀圖,透過回傳的 BarItem 設定 Bar.Fill 產生 3D 漸層效果。
- 使用
AddCurve 加入折線圖,並設定線條填充、符號與寬度。
- 設定 X 軸為文字模式 (
AxisType.Text),指派 TextLabels,並啟用 IsTicsBetweenLabels 讓群集柱條置中於標籤間距。
- 配置座標軸與窗格背景漸層。